cc.js.extend() 用法示例

extend() 源码

源码位于: CocosCreator\resources\engine\cocos2d\core\platform\js.js.

    /**
     * Derive the class from the supplied base class.
     * Both classes are just native javascript constructors, not created by cc.Class, so
     * usually you will want to inherit using {{#crossLink "cc/Class:method"}}cc.Class {{/crossLink}} instead.
     * @method extend
     * @param {Function} cls
     * @param {Function} base - the baseclass to inherit
     * @return {Function} the result class
     */
    extend: function (cls, base) {
        if (CC_DEV) {
            if (!base) {
                cc.errorID(5404);
                return;
            }
            if (!cls) {
                cc.errorID(5405);
                return;
            }
            if (Object.keys(cls.prototype).length > 0) {
                cc.errorID(5406);
            }
        }
        for (var p in base) if (base.hasOwnProperty(p)) cls[p] = base[p];
        cls.prototype = Object.create(base.prototype, {
            constructor: {
                value: cls,
                writable: true,
                configurable: true
            }
        });
        return cls;
    },

extend() 是利用 js (ES 5规范) 原生提供的方式来实现面向对象的继承, 在不继承于 cc.Node 等对象的情况下可以使用。

示例

// ------------ Base class ----------------
let BaseCls = function () {
    this.name = "base class";
    this.ok = true;
};

BaseCls.prototype.printName = function () {
    console.log(this.name);
};

// ------------ Ext class ----------------
let ExtCls = function () {
    BaseCls.call(this);
    this.name = "Ext class";
};
// extend before set new prototype functions, avoid override by extend()
cc.js.extend(ExtCls, BaseCls);
// set new prototype
ExtCls.prototype.printName = function () {
    BaseCls.prototype.printName.call(this);
    console.log("==== ext add info ===");
    console.log(this.ok);
};

var bs = new BaseCls();
bs.printName();
var ex = new ExtCls();
ex.printName();

输出:

base class
Ext class
==== ext add info ===
true

标签: js

添加新评论