CocosCreator 源码​platform/js.js详解

const tempCIDGenerater = new (require('./id-generater'))('TmpCId.');


function _getPropertyDescriptor (obj, name) {
    /* 获取指定对象自己的属性描述符。 自己的属性描述符是直接在对象上定义的属性描述符,而不是从对象的原型继承的。 */
    while (obj) {
        var pd = Object.getOwnPropertyDescriptor(obj, name);
        if (pd) {
            return pd;
        }
        obj = Object.getPrototypeOf(obj);
    }
    return null;
}
/* 
eg:
source是一个obj
name是obj的一个key
–
 */
function _copyprop(name, source, target) {
    var pd = _getPropertyDescriptor(source, name);
    Object.defineProperty(target, name, pd);
}

/**
 * !#en This module provides some JavaScript utilities. All members can be accessed with `cc.js`.
 * !#zh 这个模块封装了 JavaScript 相关的一些实用函数,你可以通过 `cc.js` 来访问这个模块。
 * @submodule js
 * @module js
 */
var js = {

    /**
     * Check the obj whether is number or not
     * If a number is created by using 'new Number(10086)', the typeof it will be "object"...
     * Then you can use this function if you care about this case.
     * @method isNumber
     * @param {*} obj
     * @returns {Boolean}
     */
    /**
     * 检查obj是否为数字
     * 如果使用“new Number(10086)”创建一个数字,它的类型将是“object”...
     * 如果您关心这种情况,则可以使用此功能。
     * @方法 isNumber
     * @param {*} 对象
     * @returns {布尔值}
     */
    isNumber: function(obj) {
        return typeof obj === 'number' || obj instanceof Number;
    },

    /**
     * Check the obj whether is string or not.
     * If a string is created by using 'new String("blabla")', the typeof it will be "object"...
     * Then you can use this function if you care about this case.
     * @method isString
     * @param {*} obj
     * @returns {Boolean}
     */
    /**
     * 检查 obj 是否为字符串。
     * 如果使用“new String(“blabla”)”创建字符串,则它的类型将是“object”...
     * 如果您关心这种情况,则可以使用此功能。
     * @方法 isString
     * @param {*} 对象
     * @returns {布尔值}
     */
    isString: function(obj) {
        return typeof obj === 'string' || obj instanceof String;
    },

    /**
     * Copy all properties not defined in obj from arguments[1...n]
     * @method addon
     * @param {Object} obj object to extend its properties
     * @param {Object} ...sourceObj source object to copy properties from
     * @return {Object} the result obj
     */
    /**
     * 从参数 [1...n] 复制 obj 中未定义的所有属性
     * @方法插件
     * @param {Object} obj 对象来扩展其属性
     * @param {Object} ...sourceObj 从中复制属性的源对象
     * @return {Object} 结果 obj
     */
    addon: function (obj) {
        'use strict';
        obj = obj || {};
        /* 
        最终结果是,把传参的参数都放到object里面
         */
        for (var i = 1, length = arguments.length; i < length; i++) {
            var source = arguments[i];
            /* eg:source 是obj
            preset: "script",__requestType__: "url"
            */
            if (source) {
                if (typeof source !== 'object') {
                    cc.errorID(5402, source);
                    continue;
                }
                for ( var name in source) {
                    if ( !(name in obj) ) {
                        _copyprop( name, source, obj);
                    }
                }
            }
        }
        /* 
        eg:
        preset: "script"
        url: "/plugins/ccservices-scripts/cocosAnalytics.min.2.2.1.js"
        __requestType__: "url" */
        return obj;
    },

    /**
     * copy all properties from arguments[1...n] to obj
     * @method mixin
     * @param {Object} obj
     * @param {Object} ...sourceObj
     * @return {Object} the result obj
     */
    /**
     * 将所有属性从arguments[1...n]复制到obj
     * @方法混合
     * @param {对象} obj
     * @param {Object} ...sourceObj
     * @return {Object} 结果 obj
     */
    mixin: function (obj) {
        'use strict';
        obj = obj || {};
        for (var i = 1, length = arguments.length; i < length; i++) {
            var source = arguments[i];
            if (source) {
                if (typeof source !== 'object') {
                    cc.errorID(5403, source);
                    continue;
                }
                for ( var name in source) {
                    _copyprop( name, source, obj);
                }
            }
        }
        return obj;
    },

    /**
     * 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
     */
    /**
     * 从提供的基类派生该类。
     * 这两个类都只是原生 javascript 构造函数,不是由 cc.Class 创建的,所以
     * 通常你会想使用 {{#crossLink "cc/Class:method"}}cc.Class {{/crossLink}} 来继承。
     * @方法扩展
     * @param {函数} cls
     * @param {Function} base -要继承的基类
     * @return {Function} 结果类
     */
    /* base 是基类, */
    extend: function (cls, base) {
        if (CC_DEV) {
            if (!base) {
                /* The base class to extend from must be non-nil
                 要扩展的基类必须非空 */
                cc.errorID(5404);
                return;
            }
            if (!cls) {
                /* The class to extend must be non-nil
                 扩展的类必须非空  */
                cc.errorID(5405);
                return;
            }
            if (Object.keys(cls.prototype).length > 0) {
                /* Class should be extended before assigning any prototype members. */
                /* 在分配任何原型成员之前应该扩展类。*/
                cc.errorID(5406);
            }
        }
        /* 遍历base里面的所有属性,赋值基类属性给cls */
        for (var p in base) if (base.hasOwnProperty(p)) cls[p] = base[p];
        /* cls的原型对象,被赋值,为cls.prototype 原型对象,创建一个纯净的obj[base的原型对象] */
        cls.prototype = Object.create(base.prototype, {
            constructor: {
                value: cls,
                writable: true,
                configurable: true
            }
        });
        return cls;
    },

    /**
     * Get super class
     * @method getSuper
     * @param {Function} ctor - the constructor of subclass
     * @return {Function}
     */

    /**
     * 获得父类
     * @方法getSuper
     * @param {Function} ctor -子类的构造函数
     * @return {函数}
     */
    getSuper (ctor) {
        var proto = ctor.prototype; //找它的原型对象  binded function do not have prototype
        var dunderProto = proto && Object.getPrototypeOf(proto);//返回对象的原型
        /* 假如 dunderProto 能转为fasle,直接返回 dunerProto,否则返回 dunderProto.constructor*/
        return dunderProto && dunderProto.constructor;
    },

    /**
     * Checks whether subclass is child of superclass or equals to superclass
     *
     * @method isChildClassOf
     * @param {Function} subclass
     * @param {Function} superclass
     * @return {Boolean}
     */
    /* 检查子类是否是超类的子类或等于超类 */
    isChildClassOf (subclass, superclass) {//eg:cc.SpriteAtlas  cc.Asset
        if (subclass && superclass) {
            if (typeof subclass !== 'function') {
                return false;
            }
            if (typeof superclass !== 'function') {
                if (CC_DEV) {
                    /* 超类应该是函数类型 */
                    /* [isChildClassOf] superclass should be function type, not */
                    cc.warnID(3625, superclass);
                }
                return false;
            }
            if (subclass === superclass) {
                return true;
            }
            for (;;) {
                /* 获取子类的父类,假如父类和传进来的父类相等,证明他们的关系就是父类和子类关系 */
                subclass = js.getSuper(subclass);
                if (!subclass) {
                    return false;
                }
                if (subclass === superclass) {
                    return true;
                }
            }
        }
        return false;
    },

    /**
     * Removes all enumerable properties from object
     * @method clear
     * @param {any} obj
     */
    /**
     * 从对象中删除所有可枚举属性
     * @方法清除
     * @param {任何} 对象
     */
    clear: function (obj) {
        var keys = Object.keys(obj);
        for (var i = 0; i < keys.length; i++) {
            delete obj[keys[i]];
        }
    },
    /* 针对delete的例子说明    
        var mapObj = Object.create(null);
        mapObj['name'] = 'tom';
        mapObj['age'] = 11;
        console.log('mapObj: ', mapObj);
        delete mapObj['name']
        console.log('mapObj: ', mapObj);

        mapObj:  [Object: null prototype] { name: 'tom', age: 11 }
        mapObj:  [Object: null prototype] { age: 11 } 
 */

    /**
     * Checks whether obj is an empty object
     * @method isEmptyObject
     * @param {any} obj 
     * @returns {Boolean}
     */
    /**
     * 检查 obj 是否为空对象
     * @方法 isEmptyObject
     * @param {任何} 对象
     * @returns {布尔值}
     */
    isEmptyObject: function (obj) {
        for (var key in obj) {
            return false;
        }
        return true;
    },

    /**
     * Get property descriptor in object and all its ancestors
     * @method getPropertyDescriptor
     * @param {Object} obj
     * @param {String} name
     * @return {Object}
     */
    /**
     * 获取对象及其所有祖先中的属性描述符
     * @方法getPropertyDescriptor
     * @param {对象} obj
     * @param {String} 名称
     * @return {对象}
     */
    getPropertyDescriptor: _getPropertyDescriptor
};

/* 声明一个对象,数据结构和obj的获取某个属性配置的obj结构一致 getOwnPropertyDescriptor */
var tmpValueDesc = {
    value: undefined,
    enumerable: false,
    writable: false,
    configurable: true
};

/**
 * Define value, just help to call Object.defineProperty.<br>
 * The configurable will be true.
 * @method value
 * @param {Object} obj
 * @param {String} prop
 * @param {any} value
 * @param {Boolean} [writable=false]
 * @param {Boolean} [enumerable=false]
 */
/**
 * 定义值,只是帮助调用Object.defineProperty。<br>
 * 可配置将是正确的。
 * @方法值
 * @param {对象} obj
 * @param {String} 道具
 * @param {任何} 值
 * @param {布尔值} [可写=]
 * @param {布尔值} [可枚举=]
 */
js.value = function (obj, prop, value, writable, enumerable) {
    tmpValueDesc.value = value;
    tmpValueDesc.writable = writable;
    tmpValueDesc.enumerable = enumerable;
    Object.defineProperty(obj, prop, tmpValueDesc);
    tmpValueDesc.value = undefined;
};


/* 声明一个obj,用来设置访问器属性 */
var tmpGetSetDesc = {
    get: null,
    set: null,
    enumerable: false,
};


/**
 * Define get set accessor, just help to call Object.defineProperty(...)
 * @method getset
 * @param {Object} obj
 * @param {String} prop
 * @param {Function} getter
 * @param {Function} [setter=null]
 * @param {Boolean} [enumerable=false]
 * @param {Boolean} [configurable=false]
 */
/**
 * 定义get set访问器,只是帮助调用Object.defineProperty(...)
 * @方法getset
 * @param {对象} obj
 * @param {String} 道具
 * @param {Function} getter
 * @param {函数} [设置器=]
 * @param {布尔值} [可枚举=]
 * @param {布尔值} [可配置=]
 */
js.getset = function (obj, prop, getter, setter, enumerable, configurable) {
    if (typeof setter !== 'function') {
        enumerable = setter;
        setter = undefined;
    }
    /* get set 赋值为 传参属性 */
    tmpGetSetDesc.get = getter;
    tmpGetSetDesc.set = setter;
    tmpGetSetDesc.enumerable = enumerable;
    tmpGetSetDesc.configurable = configurable;
    Object.defineProperty(obj, prop, tmpGetSetDesc);
    tmpGetSetDesc.get = null; //释放变量
    tmpGetSetDesc.set = null;//释放变量
};

/* 声明get 模板 obj */
var tmpGetDesc = {
    get: null,
    enumerable: false,//默认不可枚举
    configurable: false//默认不可删除
};

/**
 * Define get accessor, just help to call Object.defineProperty(...)
 * @method get
 * @param {Object} obj
 * @param {String} prop
 * @param {Function} getter
 * @param {Boolean} [enumerable=false]
 * @param {Boolean} [configurable=false]
 */
/**
 * 定义get访问器,只是帮助调用Object.defineProperty(...)
 * @方法获取
 * @param {对象} obj
 * @param {String} 道具
 * @param {Function} getter
 * @param {布尔值} [可枚举=]
 * @param {布尔值} [可配置=]
 */
js.get = function (obj, prop, getter, enumerable, configurable) {
    tmpGetDesc.get = getter;
    tmpGetDesc.enumerable = enumerable;
    tmpGetDesc.configurable = configurable;
    Object.defineProperty(obj, prop, tmpGetDesc);
    tmpGetDesc.get = null;
};

var tmpSetDesc = {
    set: null,
    enumerable: false,
    configurable: false
};

/**
 * Define set accessor, just help to call Object.defineProperty(...)
 * @method set
 * @param {Object} obj
 * @param {String} prop
 * @param {Function} setter
 * @param {Boolean} [enumerable=false]
 * @param {Boolean} [configurable=false]
 */
/**
 * 定义set访问器,只是帮助调用Object.defineProperty(...)
 * @方法集
 * @param {对象} obj
 * @param {String} 道具
 * @param {Function} 设置器
 * @param {布尔值} [可枚举=]
 * @param {布尔值} [可配置=]
 */
js.set = function (obj, prop, setter, enumerable, configurable) {
    tmpSetDesc.set = setter;
    tmpSetDesc.enumerable = enumerable;
    tmpSetDesc.configurable = configurable;
    Object.defineProperty(obj, prop, tmpSetDesc);
    tmpSetDesc.set = null;
};

/**
 * Get class name of the object, if object is just a {} (and which class named 'Object'), it will return "".
 * (modified from <a href="http://stackoverflow.com/questions/1249531/how-to-get-a-javascript-objects-class">the code from this stackoverflow post</a>)
 * @method getClassName
 * @param {Object|Function} objOrCtor - instance or constructor
 * @return {String}
 */
/**
 * 获取对象的类名,如果对象只是一个{}(以及哪个类名为“Object”),它将返回“”。
 * (修改自<a href="http://stackoverflow.com/questions/1249531/how-to-get-a-javascript-objects-class">此 stackoverflow 帖子中的代码</a>)
 * @方法getClassName
 * @param {Object|Function} objOrCtor -实例或构造函数
 * @return {字符串}
 */
js.getClassName = function (objOrCtor) {
    if (typeof objOrCtor === 'function') {
        var prototype = objOrCtor.prototype;
        if (prototype && prototype.hasOwnProperty('__classname__') && prototype.__classname__) {
            return prototype.__classname__;
        }
        var retval = '';
        //  for browsers which have name property in the constructor of the object, such as chrome
        if (objOrCtor.name) {
            retval = objOrCtor.name;
        }
        if (objOrCtor.toString) {
            var arr, str = objOrCtor.toString();
            if (str.charAt(0) === '[') {
                // str is "[object objectClass]"
                arr = str.match(/\[\w+\s*(\w+)\]/);
            }
            else {
                // str is function objectClass () {} for IE Firefox
                arr = str.match(/function\s*(\w+)/);
            }
            if (arr && arr.length === 2) {
                retval = arr[1];
            }
        }
        return retval !== 'Object' ? retval : '';
    }
    else if (objOrCtor && objOrCtor.constructor) {//存在构造函数,
        return js.getClassName(objOrCtor.constructor);
    }
    return '';
};

/* 判断id的开头是否和 模版生成器的开头一致是 “TmpCId.” */
function isTempClassId (id) {
    return typeof id !== 'string' || id.startsWith(tempCIDGenerater.prefix);
}

// id 注册,自动执行函数
(function () {
    var _idToClass = {};
    var _nameToClass = {};

    function setup (key, publicName, table) {
        js.getset(js, publicName,
            function () {
                return Object.assign({}, table);
            },
            function (value) {
                js.clear(table);
                Object.assign(table, value);
            }
        );
        return function (id, constructor) {
            // deregister old
            if (constructor.prototype.hasOwnProperty(key)) {
                delete table[constructor.prototype[key]];
            }
            js.value(constructor.prototype, key, id);
            // register class
            if (id) {
                var registered = table[id];
                if (registered && registered !== constructor) {
                    var error = 'A Class already exists with the same ' + key + ' : "' + id + '".';
                    if (CC_TEST) {
                        error += ' (This may be caused by error of unit test.) \
If you dont need serialization, you can set class id to "". You can also call \
cc.js.unregisterClass to remove the id of unused class';
                    }
                    cc.error(error);
                }
                else {
                    table[id] = constructor;
                }
                //if (id === "") {
                //    console.trace("", table === _nameToClass);
                //}
            }
        };
    }

    /**
     * Register the class by specified id, if its classname is not defined, the class name will also be set.
     * @method _setClassId
     * @param {String} classId
     * @param {Function} constructor
     * @private
     */
    /**
     * !#en All classes registered in the engine, indexed by ID.
     * !#zh 引擎中已注册的所有类型,通过 ID 进行索引。
     * @property _registeredClassIds
     * @example
     * // save all registered classes before loading scripts
     * let builtinClassIds = cc.js._registeredClassIds;
     * let builtinClassNames = cc.js._registeredClassNames;
     * // load some scripts that contain CCClass
     * ...
     * // clear all loaded classes
     * cc.js._registeredClassIds = builtinClassIds;
     * cc.js._registeredClassNames = builtinClassNames;
     */
    js._setClassId = setup('__cid__', '_registeredClassIds', _idToClass);

    /**
     * !#en All classes registered in the engine, indexed by name.
     * !#zh 引擎中已注册的所有类型,通过名称进行索引。
     * @property _registeredClassNames
     * @example
     * // save all registered classes before loading scripts
     * let builtinClassIds = cc.js._registeredClassIds;
     * let builtinClassNames = cc.js._registeredClassNames;
     * // load some scripts that contain CCClass
     * ...
     * // clear all loaded classes
     * cc.js._registeredClassIds = builtinClassIds;
     * cc.js._registeredClassNames = builtinClassNames;
     */
    var doSetClassName = setup('__classname__', '_registeredClassNames', _nameToClass);

    /**
     * Register the class by specified name manually
     * @method setClassName
     * @param {String} className
     * @param {Function} constructor
     */
    js.setClassName = function (className, constructor) {
        doSetClassName(className, constructor);
        // auto set class id
        if (!constructor.prototype.hasOwnProperty('__cid__')) {
            var id = className || tempCIDGenerater.getNewId();
            if (id) {
                js._setClassId(id, constructor);
            }
        }
    };

    /**
     * Unregister a class from fireball.
     *
     * If you dont need a registered class anymore, you should unregister the class so that Fireball will not keep its reference anymore.
     * Please note that its still your responsibility to free other references to the class.
     *
     * @method unregisterClass
     * @param {Function} ...constructor - the class you will want to unregister, any number of classes can be added
     */
    /**
     * 从fireball中取消注册一个类。
     *
     * 如果您不再需要已注册的类,则应取消注册该类,以便 Fireball 不再保留其引用。
     * 请注意,您仍然有责任释放对该类的其他引用。
     *
     * @方法注销类
     * @param {Function} ...构造函数 -您要取消注册的类,可以添加任意数量的类
     */
    js.unregisterClass = function () {
        for (var i = 0; i < arguments.length; i++) {
            var p = arguments[i].prototype;
            var classId = p.__cid__;
            if (classId) {
                delete _idToClass[classId];
            }
            var classname = p.__classname__;
            if (classname) {
                delete _nameToClass[classname];
            }
        }
    };

    /**
     * Get the registered class by id
     * @method _getClassById
     * @param {String} classId
     * @return {Function} constructor
     * @private
     */
    /**
     * 通过id获取注册的类
     * @方法_getClassById
     * @param {String} 类ID
     * @return {Function} 构造函数
     * @私人的
     */
    js._getClassById = function (classId) {
        return _idToClass[classId];
    };

    /**
     * Get the registered class by name
     * @method getClassByName
     * @param {String} classname
     * @return {Function} constructor
     */
    /**
     * 通过名称获取注册的类
     * @方法 getClassByName
     * @param {String} 类名
     * @return {Function} 构造函数
     */
    js.getClassByName = function (classname) {
        return _nameToClass[classname];
    };

    /**
     * Get class id of the object
     * @method _getClassId
     * @param {Object|Function} obj - instance or constructor
     * @param {Boolean} [allowTempId=true] - can return temp id in editor
     * @return {String}
     * @private
     */
    /**
     * 获取对象的类id
     * @方法_getClassId
     * @param {Object|Function} obj -实例或构造函数
     * @param {Boolean} [allowTempId=] -可以在编辑器中返回临时 ID
     * @return {字符串}
     * @私人的
     */
    js._getClassId = function (obj, allowTempId) {
        allowTempId = (typeof allowTempId !== 'undefined' ? allowTempId: true);

        var res;
        if (typeof obj === 'function' && obj.prototype.hasOwnProperty('__cid__')) {
            res = obj.prototype.__cid__;
            if (!allowTempId && (CC_DEV || CC_EDITOR) && isTempClassId(res)) {
                return '';
            }
            return res;
        }
        if (obj && obj.constructor) {
            var prototype = obj.constructor.prototype;
            if (prototype && prototype.hasOwnProperty('__cid__')) {
                res = obj.__cid__;
                if (!allowTempId && (CC_DEV || CC_EDITOR) && isTempClassId(res)) {
                    return '';
                }
                return res;
            }
        }
        return '';
    };
})();

/**
 * Defines a polyfill field for deprecated codes.
 * @method obsolete
 * @param {any} obj - YourObject or YourClass.prototype
 * @param {String} obsoleted - "OldParam" or "YourClass.OldParam"
 * @param {String} newExpr - "NewParam" or "YourClass.NewParam"
 * @param {Boolean} [writable=false]
 */
js.obsolete = function (obj, obsoleted, newExpr, writable) {
    var extractPropName = /([^.]+)$/;
    var oldProp = extractPropName.exec(obsoleted)[0];
    var newProp = extractPropName.exec(newExpr)[0];
    function get () {
        if (CC_DEV) {
            cc.warnID(1400, obsoleted, newExpr);
        }
        return this[newProp];
    }
    if (writable) {
        js.getset(obj, oldProp,
            get,
            function (value) {
                if (CC_DEV) {
                    cc.warnID(1400, obsoleted, newExpr);
                }
                this[newProp] = value;
            }
        );
    }
    else {
        js.get(obj, oldProp, get);
    }
};

/**
 * Defines all polyfill fields for obsoleted codes corresponding to the enumerable properties of props.
 * @method obsoletes
 * @param {any} obj - YourObject or YourClass.prototype
 * @param {any} objName - "YourObject" or "YourClass"
 * @param {Object} props
 * @param {Boolean} [writable=false]
 */
js.obsoletes = function (obj, objName, props, writable) {
    for (var obsoleted in props) {
        var newName = props[obsoleted];
        js.obsolete(obj, objName + '.' + obsoleted, newName, writable);
    }
};

var REGEXP_NUM_OR_STR = /(%d)|(%s)/;
var REGEXP_STR = /%s/;

/**
 * A string tool to construct a string with format string.
 * @method formatStr
 * @param {String|any} msg - A JavaScript string containing zero or more substitution strings (%s).
 * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output.
 * @returns {String}
 * @example
 * cc.js.formatStr("a: %s, b: %s", a, b);
 * cc.js.formatStr(a, b, c);
 */
js.formatStr = function () {
    var argLen = arguments.length;
    if (argLen === 0) {
        return '';
    }
    var msg = arguments[0];
    if (argLen === 1) {
        return '' + msg;
    }

    var hasSubstitution = typeof msg === 'string' && REGEXP_NUM_OR_STR.test(msg);
    if (hasSubstitution) {
        for (let i = 1; i < argLen; ++i) {
            var arg = arguments[i];
            var regExpToTest = typeof arg === 'number' ? REGEXP_NUM_OR_STR : REGEXP_STR;
            if (regExpToTest.test(msg))
                msg = msg.replace(regExpToTest, arg);
            else
                msg += ' ' + arg;
        }
    }
    else {
        for (let i = 1; i < argLen; ++i) {
            msg += ' ' + arguments[i];
        }
    }
    return msg;
};

// see https://github.com/petkaantonov/bluebird/issues/1389
js.shiftArguments = function () {
    var len = arguments.length - 1;
    var args = new Array(len);
    for(var i = 0; i < len; ++i) {
        args[i] = arguments[i + 1];
    }
    return args;
};

/**
 * !#en
 * A simple wrapper of `Object.create(null)` which ensures the return object have no prototype (and thus no inherited members). So we can skip `hasOwnProperty` calls on property lookups. It is a worthwhile optimization than the `{}` literal when `hasOwnProperty` calls are necessary.
 * !#zh
 * 该方法是对 `Object.create(null)` 的简单封装。`Object.create(null)` 用于创建无 prototype (也就无继承)的空对象。这样我们在该对象上查找属性时,就不用进行 `hasOwnProperty` 判断。在需要频繁判断 `hasOwnProperty` 时,使用这个方法性能会比 `{}` 更高。
 *
 * @method createMap
 * @param {Boolean} [forceDictMode=false] - Apply the delete operator to newly created map object. This causes V8 to put the object in "dictionary mode" and disables creation of hidden classes which are very expensive for objects that are constantly changing shape.
 * @return {Object}
 */
js.createMap = function (forceDictMode) {
    /* 创建空对象 */
    var map = Object.create(null);
    
    if (forceDictMode) {
        const INVALID_IDENTIFIER_1 = '.';
        const INVALID_IDENTIFIER_2 = '/';
        map[INVALID_IDENTIFIER_1] = true;
        map[INVALID_IDENTIFIER_2] = true;
        delete map[INVALID_IDENTIFIER_1];
        delete map[INVALID_IDENTIFIER_2];
    }
    return map;
};

/**
 * @class array
 * @static
 */

/**
 * Removes the array item at the specified index.
 * @method removeAt
 * @param {any[]} array
 * @param {Number} index
 */
function removeAt (array, index) {
    array.splice(index, 1);
}

/**
 * Removes the array item at the specified index.
 * It's faster but the order of the array will be changed.
 * @method fastRemoveAt
 * @param {any[]} array
 * @param {Number} index
 */
/**
 * 删除指定索引处的数组项。
 * 它更快,但数组的顺序会改变。
 * @方法fastRemoveAt
 * @param {any[]} 数组
 * @param {Number} 索引
 */
/* 原来位置的值,被替换为最后一位的值,--长度后,最后一位丢弃,实现不是每个位置都移动 */
function fastRemoveAt (array, index) {
    var length = array.length;
    if (index < 0 || index >= length) {
        return;
    }
    array[index] = array[length - 1];
    array.length = length - 1;
}

/**
 * Removes the first occurrence of a specific object from the array.
 * @method remove
 * @param {any[]} array
 * @param {any} value
 * @return {Boolean}
 */
function remove (array, value) {
    var index = array.indexOf(value);
    if (index >= 0) {
        removeAt(array, index);
        return true;
    }
    else {
        return false;
    }
}

/**
 * Removes the first occurrence of a specific object from the array.
 * It's faster but the order of the array will be changed.
 * @method fastRemove
 * @param {any[]} array
 * @param {Number} value
 */
/* 移除首个指定的数组元素。判定元素相等时相当于于使用了 Array.prototype.indexOf。
 此函数十分高效,但会改变数组的元素次序。
 
 注意,这个函数有风险,因为会改变原来数组的顺序,
 假如仅仅是 遍历value,不对顺序做要求是可以的;
 具体如下:
 */

 /* 
let array = [1, 2, 3, 4, 5, 6, 7, 8];
/* array:  [
  1, 2, 3, 4,5, 6, 7,8
] 
function fastRemove (array, value) {
    var index = array.indexOf(value);
    if (index >= 0) {
        array[index] = array[array.length - 1];
        --array.length;
    }
}
fastRemove(array, 5)
console.log('array: ', array);
/* array:  [
  1, 2, 3, 4, 8, 6, 7]
  可以看到数组的顺序修改了,最后一个位置的value修改到了 删除处的位置,
  非单线程的语言,这种思路一定有问题,会导致数组遍历出问题
  【假如用链表生成一个数组,就能高效处理删除这种情况了。】
  */
function fastRemove (array, value) {
    var index = array.indexOf(value);
    if (index >= 0) {
        array[index] = array[array.length - 1];
        --array.length;
    }
}

/**
 * Verify array's Type
 * @method verifyType
 * @param {array} array
 * @param {Function} type
 * @return {Boolean}
 */
function verifyType (array, type) {
    if (array && array.length > 0) {
        for (var i = 0; i < array.length; i++) {
            if (!(array[i] instanceof  type)) {
                cc.logID(1300);
                return false;
            }
        }
    }
    return true;
}

/**
 * Removes from array all values in minusArr. For each Value in minusArr, the first matching instance in array will be removed.
 * @method removeArray
 * @param {Array} array Source Array
 * @param {Array} minusArr minus Array
 */
function removeArray (array, minusArr) {
    for (var i = 0, l = minusArr.length; i < l; i++) {
        remove(array, minusArr[i]);
    }
}

/**
 * Inserts some objects at index
 * @method appendObjectsAt
 * @param {Array} array
 * @param {Array} addObjs
 * @param {Number} index
 * @return {Array}
 */
function appendObjectsAt (array, addObjs, index) {
    array.splice.apply(array, [index, 0].concat(addObjs));
    return array;
}

/**
 * Determines whether the array contains a specific value.
 * @method contains
 * @param {any[]} array
 * @param {any} value
 * @return {Boolean}
 */
function contains (array, value) {
    return array.indexOf(value) >= 0;
}

/**
 * Copy an array's item to a new array (its performance is better than Array.slice)
 * @method copy
 * @param {Array} array
 * @return {Array}
 */
function copy (array) {
    var i, len = array.length, arr_clone = new Array(len);
    for (i = 0; i < len; i += 1)
        arr_clone[i] = array[i];
    return arr_clone;
}

js.array = {
    remove,
    fastRemove,
    removeAt,
    fastRemoveAt,
    contains,
    verifyType,
    removeArray,
    appendObjectsAt,
    copy,
    MutableForwardIterator: require('../utils/mutable-forward-iterator')
};

// OBJECT POOL

/**
 * !#en
 * A fixed-length object pool designed for general type.<br>
 * The implementation of this object pool is very simple,
 * it can helps you to improve your game performance for objects which need frequent release and recreate operations<br/>
 * !#zh
 * 长度固定的对象缓存池,可以用来缓存各种对象类型。<br/>
 * 这个对象池的实现非常精简,它可以帮助您提高游戏性能,适用于优化对象的反复创建和销毁。
 * @class Pool
 * @example
 *
 *Example 1:
 *
 *function Details () {
 *    this.uuidList = [];
 *};
 *Details.prototype.reset = function () {
 *    this.uuidList.length = 0;
 *};
 *Details.pool = new js.Pool(function (obj) {
 *    obj.reset();
 *}, 5);
 *Details.pool.get = function () {
 *    return this._get() || new Details();
 *};
 *
 *var detail = Details.pool.get();
 *...
 *Details.pool.put(detail);
 *
 *Example 2:
 *
 *function Details (buffer) {
 *    this.uuidList = buffer;
 *};
 *...
 *Details.pool.get = function (buffer) {
 *    var cached = this._get();
 *    if (cached) {
 *        cached.uuidList = buffer;
 *        return cached;
 *    }
 *    else {
 *        return new Details(buffer);
 *    }
 *};
 *
 *var detail = Details.pool.get( [] );
 *...
 */
/**
 * !#en
 * Constructor for creating an object pool for the specific object type.
 * You can pass a callback argument for process the cleanup logic when the object is recycled.
 * !#zh
 * 使用构造函数来创建一个指定对象类型的对象池,您可以传递一个回调函数,
 * 用于处理对象回收时的清理逻辑。
 * @method constructor
 * @param {Function} [cleanupFunc] - the callback method used to process the cleanup logic when the object is recycled.
 * @param {Object} cleanupFunc.obj
 * @param {Number} size - initializes the length of the array
 * @typescript
 * constructor(cleanupFunc: (obj: any) => void, size: number)
 * constructor(size: number)
 */

function Pool (cleanupFunc, size) {
    if (size === undefined) {
        /* 因为js没有校验参数,第一个有可能直接就是参数size,第一个参数为空,
        所以这里用第1个参数当size用的情况,感觉像是个容错处理 */
        size = cleanupFunc;
        cleanupFunc = null;
    }
    this.get = null;
    /* 初始化当前对象池中的对象数量=0
    当前可用对象数量,一开始默认是 0,随着对象的回收会逐渐增大,
    最大不会超过调用构造函数时指定的 size。
 */
    this.count = 0;
    /* 创建一个数组,长度为size */
    this._pool = new Array(size);
    /* 设置一个本地的回收global 函数 为 传入的model 函数 */
    this._cleanup = cleanupFunc;
}

/**
 * !#en
 * Get and initialize an object from pool. This method defaults to null and requires the user to implement it.
 * !#zh
 * 获取并初始化对象池中的对象。这个方法默认为空,需要用户自己实现。
 * @method get
 * @param {any} ...params - parameters to used to initialize the object
 * @returns {Object}
 */

/**
 * !#en
 * The current number of available objects, the default is 0, it will gradually increase with the recycle of the object,
 * the maximum will not exceed the size specified when the constructor is called.
 * !#zh
 * 当前可用对象数量,一开始默认是 0,随着对象的回收会逐渐增大,最大不会超过调用构造函数时指定的 size。
 * @property {Number} count
 * @default 0
 */

/**
 * !#en
 * Get an object from pool, if no available object in the pool, null will be returned.
 * !#zh
 * 获取对象池中的对象,如果对象池没有可用对象,则返回空。
 * @method _get
 * @returns {Object|null}
 */
Pool.prototype._get = function () {
    if (this.count > 0) {
        /* 可用对象数量减一 */
        --this.count;
        /* 获取数组的最后一个位置的item */
        var cache = this._pool[this.count];
        /* 数组最后一个位置,指针指向新对象 null,cache不变,直线原来arr的元素对应的内存地址 */
        this._pool[this.count] = null;
        return cache;//这里不会受影响,
    }
    return null;
};

/**
 * !#en Put an object into the pool.
 * !#zh 向对象池返还一个不再需要的对象。
 * @method put
 */
Pool.prototype.put = function (obj) {
    var pool = this._pool;
    /* 当当前总数量,小于数组最大容纳 长度的时候 */
    if (this.count < pool.length) {
        /* 整个调用,要么函数为空,要么函数一定返回true,所以目前下面判断应该不会用到 */
        if (this._cleanup && this._cleanup(obj) === false) {
            return;
        }
        /* 插入数据 ,count个数++ */
        pool[this.count] = obj;
        /* 当前总数量++ */
        ++this.count;
    }
};

/**
 * !#en Resize the pool.
 * !#zh 设置对象池容量。
 * @method resize
 */
Pool.prototype.resize = function (length) {
    if (length >= 0) {
        this._pool.length = length;
        /* 如果当前总数量大于数组最大容纳 长度的时候 ,设置值为最大容量 */
        if (this.count > length) {
            this.count = length;
        }
    }
};

js.Pool = Pool;

//

cc.js = js;

module.exports = js;

// fix submodule pollute ...
/**
 * @submodule cc
 */

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值