From 4bedb8a99305bcb4d8f4c2d7e52dc9389d8de811 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 26 Oct 2016 17:24:45 +0800 Subject: [PATCH 1/5] minor tweaks --- cocos2d/core/CCNode.js | 21 +-- cocos2d/core/assets/CCPrefab.js | 17 +-- cocos2d/core/base-nodes/CCSGNode.js | 2 - cocos2d/core/components/CCComponent.js | 10 +- cocos2d/core/platform/CCClass.js | 2 +- cocos2d/core/platform/instantiate.js | 193 +++++++++++++------------ test/qunit/unit/test-instantiate.js | 4 +- 7 files changed, 122 insertions(+), 127 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index f610232671..e20f9d6694 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -457,8 +457,7 @@ var Node = cc.Class({ } }, - ctor: function () { - var name = arguments[0]; + ctor: function (name) { this._name = typeof name !== 'undefined' ? name : 'New Node'; this._activeInHierarchy = false; @@ -1089,27 +1088,29 @@ var Node = cc.Class({ } }, - _instantiate: function () { - var clone = cc.instantiate._clone(this, this); - clone._parent = null; + _instantiate: function (cloned) { + if (!cloned) { + cloned = cc.instantiate._clone(this, this); + } var thisPrefabInfo = this._prefab; var syncing = thisPrefabInfo && this === thisPrefabInfo.root && thisPrefabInfo.sync; if (syncing) { // copy non-serialized property - clone._prefab._synced = thisPrefabInfo._synced; + cloned._prefab._synced = thisPrefabInfo._synced; //if (thisPrefabInfo._synced) { // return clone; //} } else if (CC_EDITOR && cc.engine._isPlaying) { - this._name += ' (Clone)'; + cloned._name += ' (Clone)'; } - // init - clone._onBatchCreated(); + // reset and init + cloned._parent = null; + cloned._onBatchCreated(); - return clone; + return cloned; }, // EVENTS diff --git a/cocos2d/core/assets/CCPrefab.js b/cocos2d/core/assets/CCPrefab.js index c618e5d9f2..98b7889a21 100644 --- a/cocos2d/core/assets/CCPrefab.js +++ b/cocos2d/core/assets/CCPrefab.js @@ -23,28 +23,21 @@ THE SOFTWARE. ****************************************************************************/ -function visitWrapper (wrapper, visitor) { - visitor(wrapper); - - var children = wrapper._children; - for (var i = 0; i < children.length; i++) { - visitor(children[i]); - } -} - /** * !#en Class for prefab handling. * !#zh 预制资源类。 * @class Prefab * @extends Asset - * */ var Prefab = cc.Class({ name: 'cc.Prefab', extends: cc.Asset, properties: { - data: null + /** + * @property {Node} data - the main cc.Node in the prefab + */ + data: null, }, createNode: function (cb) { @@ -65,7 +58,7 @@ var Prefab = cc.Class({ } // instantiate - var node = cc.instantiate(this.data); + var node = this.data._instantiate(); if (CC_EDITOR || CC_TEST) { // This operation is not necessary, but some old prefab asset may not contain complete data. diff --git a/cocos2d/core/base-nodes/CCSGNode.js b/cocos2d/core/base-nodes/CCSGNode.js index db0937e745..38a943c377 100644 --- a/cocos2d/core/base-nodes/CCSGNode.js +++ b/cocos2d/core/base-nodes/CCSGNode.js @@ -154,8 +154,6 @@ _ccsg.Node = cc.Class({ }, ctor: function() { - var name = arguments[0]; - this.__instanceId = cc.ClassManager.getNewInstanceId(); this._running = false; diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index 05e11a688f..9ec19d7a31 100644 --- a/cocos2d/core/components/CCComponent.js +++ b/cocos2d/core/components/CCComponent.js @@ -754,10 +754,12 @@ var Component = cc.Class({ _destruct: Misc.destructIgnoreId, - _instantiate: function () { - var clone = cc.instantiate._clone(this, this); - clone.node = null; - return clone; + _instantiate: function (cloned) { + if (!cloned) { + cloned = cc.instantiate._clone(this, this); + } + cloned.node = null; + return cloned; }, // Scheduler diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index afb2ce970c..40f16e8e88 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -468,7 +468,7 @@ function _checkCtor (ctor, className) { cc.error('ctor of "%s" must be function type', className); return; } - if (ctor.length > 0) { + if (ctor.length > 0 && !className.startsWith('cc.')) { // fireball-x/dev#138: To make a unified CCClass serialization process, // we don't allow parameters for constructor when creating instances of CCClass. // For advance user, construct arguments can still get from 'arguments'. diff --git a/cocos2d/core/platform/instantiate.js b/cocos2d/core/platform/instantiate.js index 9feb76de04..c745cc5fb5 100644 --- a/cocos2d/core/platform/instantiate.js +++ b/cocos2d/core/platform/instantiate.js @@ -24,6 +24,7 @@ ****************************************************************************/ var CCObject = require('./CCObject'); +var Destroyed = CCObject.Flags.Destroyed; var PersistentMask = CCObject.Flags.PersistentMask; var Attr = require('./attribute'); var _isDomNode = require('./utils').isDomNode; @@ -57,7 +58,7 @@ function instantiate (original) { } return null; } - if (original instanceof CCObject && !original.isValid) { + if (!cc.isValid(original)) { if (CC_DEV) { cc.error('The thing you want to instantiate is destroyed'); } @@ -66,7 +67,12 @@ function instantiate (original) { var clone; if (original instanceof CCObject) { - // invoke _instantiate method if supplied + // Invoke _instantiate method if supplied. + // The _instantiate callback will be called only on the root object, its associated object will not be called. + // @callback associated + // @param {Object} [instantiated] - If supplied, _instantiate just need to initialize the instantiated object, + // no need to create new object by itself. + // @returns {Object} - the instantiated object if (original._instantiate) { cc.game._isCloning = true; clone = original._instantiate(); @@ -88,18 +94,13 @@ function instantiate (original) { return clone; } -/* - * Reserved tags: - * - _iN$t: the cloned instance - */ - -var objsToClearTmpVar = []; // 用于重设临时变量 +var objsToClearTmpVar = []; // used to reset _iN$t variable ///** // * Do instantiate object, the object to instantiate must be non-nil. // * 这是一个通用的 instantiate 方法,可能效率比较低。 // * 之后可以给各种类型重写快速实例化的特殊实现,但应该在单元测试中将结果和这个方法的结果进行对比。 -// * 值得注意的是,这个方法不可重入,不支持 mixin。 +// * 值得注意的是,这个方法不可重入。 // * // * @param {Object} obj - 该方法仅供内部使用,用户需负责保证参数合法。什么参数是合法的请参考 cc.instantiate 的实现。 // * @param {Node} [parent] - 只有在该对象下的场景物体会被克隆。 @@ -108,23 +109,29 @@ var objsToClearTmpVar = []; // 用于重设临时变量 // */ function doInstantiate (obj, parent) { if (Array.isArray(obj)) { - cc.error('Can not instantiate array'); + if (CC_DEV) { + cc.error('Can not instantiate array'); + } return null; } if (!CC_JSB && _isDomNode && _isDomNode(obj)) { - cc.error('Can not instantiate DOM element'); + if (CC_DEV) { + cc.error('Can not instantiate DOM element'); + } return null; } var clone; if (obj._iN$t) { clone = obj._iN$t; + // enumerateObject will always push obj to objsToClearTmpVar } else { // User can specify an existing object by assigning the "_iN$t" property var klass = obj.constructor; clone = new klass(); } + enumerateObject(obj, clone, parent); for (var i = 0, len = objsToClearTmpVar.length; i < len; ++i) { @@ -135,53 +142,56 @@ function doInstantiate (obj, parent) { return clone; } +var SERIALIZABLE = Attr.DELIMETER + 'serializable'; // @param {Object} obj - The object to instantiate, typeof must be 'object' and should not be an array. -function enumerateObject (obj, clone, parent) { - var value, type, key; - var klass = obj.constructor; - obj._iN$t = clone; - objsToClearTmpVar.push(obj); - if (cc.Class._isCCClass(klass)) { - var DELIMETER = Attr.DELIMETER; - var props = klass.__props__; - var attrs = Attr.getClassAttrs(klass); - for (var p = 0; p < props.length; p++) { - key = props[p]; - if (attrs[key + DELIMETER + 'serializable'] !== false) { - value = obj[key]; - type = typeof value; - if (type === 'object') { - clone[key] = value ? instantiateObj(value, parent, clone, key) : value; - } - else { - clone[key] = (type !== 'function') ? value : null; - } + +function enumerateCCClass (klass, obj, clone, parent) { + var props = klass.__props__; + var attrs = Attr.getClassAttrs(klass); + for (var p = 0; p < props.length; p++) { + var key = props[p]; + if (attrs[key + SERIALIZABLE] !== false) { + var value = obj[key]; + if (typeof value === 'object' && value) { + clone[key] = value._iN$t || instantiateObj(value, parent); + } + else { + clone[key] = value; } } - if (CC_EDITOR && (clone instanceof cc._BaseNode || clone instanceof cc.Component)) { - clone._id = ''; - } + } + if (CC_EDITOR && (obj instanceof cc._BaseNode || obj instanceof cc.Component)) { + clone._id = ''; + } +} + +function enumerateObject (obj, clone, parent) { + // 目前使用“_iN$t”这个特殊字段来存实例化后的对象,这样做主要是为了防止循环引用 + // 注意,为了避免循环引用,所有新创建的实例,必须在赋值前被设为源对象的_iN$t + obj._iN$t = clone; + objsToClearTmpVar.push(obj); + var klass = obj.constructor; + if (cc.Class._isCCClass(klass)) { + enumerateCCClass(klass, obj, clone, parent); } else { // primitive javascript object - for (key in obj) { - if ( !obj.hasOwnProperty(key) || - // starts with "__" but not "__type__" - (key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && key !== '__type__') - ) { + for (var key in obj) { + if (!obj.hasOwnProperty(key) || + (key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && // starts with "__" + key !== '__type__') + ) { continue; } - value = obj[key]; - if (value === clone) { - continue; // value is obj._iN$t - } - // instantiate field - type = typeof value; - if (type === 'object') { - clone[key] = value ? instantiateObj(value, parent, clone, key) : value; + var value = obj[key]; + if (typeof value === 'object' && value) { + if (value === clone) { + continue; // value is obj._iN$t + } + clone[key] = value._iN$t || instantiateObj(value, parent); } else { - clone[key] = (type !== 'function') ? value : null; + clone[key] = value; } } } @@ -190,80 +200,71 @@ function enumerateObject (obj, clone, parent) { } } -///** -// * @return {Object} - the original non-nil object, typeof must be 'object' -// */ -function instantiateObj (obj, parent, ownerObj, ownerKey) { - // 目前使用“_iN$t”这个特殊字段来存实例化后的对象,这样做主要是为了防止循环引用 - // 注意,为了避免循环引用,所有新创建的实例,必须在赋值前被设为源对象的_iN$t - var clone = obj._iN$t; - if (clone) { - // has been instantiated - return clone; +/* + * @param {Object|Array} obj - the original non-nil object, typeof must be 'object' + * @return {Object|Array} - the original non-nil object, typeof must be 'object' + */ +function instantiateObj (obj, parent) { + if (obj instanceof cc.ValueType) { + return obj.clone(); } - - if ( !cc.isValid(obj) ) { - return null; - } - if (obj instanceof cc.Asset) { // 所有资源直接引用,不需要拷贝 return obj; } - else if (Array.isArray(obj)) { + var clone; + if (Array.isArray(obj)) { var len = obj.length; clone = new Array(len); obj._iN$t = clone; for (var i = 0; i < len; ++i) { var value = obj[i]; - // instantiate field - var type = typeof value; - if (type === 'object') { - clone[i] = value ? instantiateObj(value, parent, clone, '' + i) : value; + if (typeof value === 'object' && value) { + clone[i] = value._iN$t || instantiateObj(value, parent); } else { - clone[i] = (type !== 'function') ? value : null; + clone[i] = value; } } objsToClearTmpVar.push(obj); return clone; } - else if (obj instanceof cc.ValueType) { - return obj.clone(); + else if (obj._objFlags & Destroyed) { + // the same as cc.isValid(obj) + return null; } - else { - var ctor = obj.constructor; - if (cc.Class._isCCClass(ctor)) { - if (parent) { - if (parent instanceof cc.Component) { - if (obj instanceof cc._BaseNode || obj instanceof cc.Component) { + + var ctor = obj.constructor; + if (cc.Class._isCCClass(ctor)) { + if (parent) { + if (parent instanceof cc.Component) { + if (obj instanceof cc._BaseNode || obj instanceof cc.Component) { + return obj; + } + } + else if (parent instanceof cc._BaseNode) { + if (obj instanceof cc._BaseNode) { + if (!obj.isChildOf(parent)) { + // should not clone other nodes if not descendant return obj; } } - else if (parent instanceof cc._BaseNode) { - if (obj instanceof cc._BaseNode) { - if (!obj.isChildOf(parent)) { - // should not clone other nodes if not descendant - return obj; - } - } - else if (obj instanceof cc.Component) { - if (!obj.node.isChildOf(parent)) { - // should not clone other component if not descendant - return obj; - } + else if (obj instanceof cc.Component) { + if (!obj.node.isChildOf(parent)) { + // should not clone other component if not descendant + return obj; } } } } - else if (ctor !== Object) { - // unknown type - return obj; - } - clone = new ctor(); - enumerateObject(obj, clone, parent); - return clone; } + else if (ctor !== Object) { + // unknown type + return obj; + } + clone = new ctor(); + enumerateObject(obj, clone, parent); + return clone; } instantiate._clone = doInstantiate; diff --git a/test/qunit/unit/test-instantiate.js b/test/qunit/unit/test-instantiate.js index bdd6d05b2d..7bd1d32fd5 100644 --- a/test/qunit/unit/test-instantiate.js +++ b/test/qunit/unit/test-instantiate.js @@ -199,7 +199,7 @@ var clone = cc.instantiate(node); - strictEqual(clone.getComponent(Script).compRef, null, 'deleted object should be nullify'); + ok(clone.getComponent(Script).compRef === null, 'deleted object should be nullify'); }); test('redirect reference', function () { @@ -248,7 +248,7 @@ var cloneChildComp = cloneChild.getComponent(Script); notEqual(child, cloneChild, 'should clone child'); - strictEqual(cloneChild.parent, cloneParent, 'should redirect parent reference'); + ok(cloneChild.parent === cloneParent, 'should redirect parent reference'); ok(cloneParentComp.nodeInComp === cloneChild, 'should redirect child reference'); fastArrayEqual(cloneParentComp.nodeArrayInComp, [cloneChild, other], 'should redirect array of child reference'); From b22b36ea58d238c0c85c152feac045f0913e52c1 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 2 Nov 2016 20:49:12 +0800 Subject: [PATCH 2/5] bake instantiate codes (JIT) --- cocos2d/core/assets/CCPrefab.js | 41 ++- cocos2d/core/platform/index.js | 1 + cocos2d/core/platform/instantiate-jit.js | 426 +++++++++++++++++++++++ cocos2d/core/utils/prefab-helper.js | 11 +- test/qunit/unit/test-instantiate.js | 60 +++- test/qunit/unit/test-prefab.js | 8 +- 6 files changed, 513 insertions(+), 34 deletions(-) create mode 100644 cocos2d/core/platform/instantiate-jit.js diff --git a/cocos2d/core/assets/CCPrefab.js b/cocos2d/core/assets/CCPrefab.js index 98b7889a21..4680e6cdd5 100644 --- a/cocos2d/core/assets/CCPrefab.js +++ b/cocos2d/core/assets/CCPrefab.js @@ -38,6 +38,16 @@ var Prefab = cc.Class({ * @property {Node} data - the main cc.Node in the prefab */ data: null, + + /** + * Cache function for fast instantiation + * @property {Function} _createFunction + * @private + */ + _createFunction: { + default: null, + serializable: false + } }, createNode: function (cb) { @@ -47,7 +57,21 @@ var Prefab = cc.Class({ } }, - _instantiate: function () { + /** + * Dynamically translation prefab data into minimized code.
+ * This method will be called automatically before the first time the prefab being instantiated, + * but you can re-call to refresh the create function once you modified the original prefab data in script. + * @method compileCreateFunction + */ + compileCreateFunction: function () { + var jit = require('../platform/instantiate-jit'); + this._createFunction = jit.compile(this.data); + }, + + // just instantiate, will not initialize the Node, this will be called during Node's initialization. + // @param {Node} [rootToRedirect] - specify an instantiated prefabRoot that all references to prefabRoot in prefab + // will redirect to + _doInstantiate: function (rootToRedirect) { if (this.data._prefab) { // prefab asset is always synced this.data._prefab._synced = true; @@ -56,15 +80,22 @@ var Prefab = cc.Class({ // temp guard code cc.warn('internal error: _prefab is undefined'); } + if (!this._createFunction) { + this.compileCreateFunction(); + } + return this._createFunction(rootToRedirect); // this.data._instantiate(); + }, - // instantiate - var node = this.data._instantiate(); - + _instantiate: function () { + // instantiate node + var node = this._doInstantiate(); + // initialize node + this.data._instantiate(node); + // link prefab in editor if (CC_EDITOR || CC_TEST) { // This operation is not necessary, but some old prefab asset may not contain complete data. _Scene.PrefabUtils.linkPrefab(this, node); } - return node; } }); diff --git a/cocos2d/core/platform/index.js b/cocos2d/core/platform/index.js index c4c74cd209..7c384a6b4a 100644 --- a/cocos2d/core/platform/index.js +++ b/cocos2d/core/platform/index.js @@ -30,6 +30,7 @@ require('./callbacks-invoker'); require('./url'); require('./deserialize'); require('./instantiate'); +require('./instantiate-jit'); require('./requiring-frame'); require('./CCSys'); require('./CCMacro'); diff --git a/cocos2d/core/platform/instantiate-jit.js b/cocos2d/core/platform/instantiate-jit.js new file mode 100644 index 0000000000..606e66ea0f --- /dev/null +++ b/cocos2d/core/platform/instantiate-jit.js @@ -0,0 +1,426 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +// Some helper methods for compile instantiation code + +var CCObject = require('./CCObject'); +var Destroyed = CCObject.Flags.Destroyed; +var PersistentMask = CCObject.Flags.PersistentMask; +var Attr = require('./attribute'); +var JS = require('./js'); + +var SERIALIZABLE = Attr.DELIMETER + 'serializable'; +var DEFAULT = Attr.DELIMETER + 'default'; + +var NAME_IN_DOT_NOTATION_REG = /^[$A-Za-z_][0-9A-Za-z_$]*$/; +var VAR = 'var '; +var LOCAL_OBJ = 'o'; +var NEW = 'new '; +var SCOPE_START = '(function'; +var SCOPE_END = 'return o;})'; +var LINE_INDEX_OF_NEW_OBJ = 0; + +function equalsToDefault (def, value) { + if (typeof def === 'function') { + try { + def = def(); + } + catch (e) { + return false; + } + } + if (def === value) { + return true; + } + if (def && value) { + if (def instanceof cc.ValueType && def.equals(value)) { + return true; + } + if ((Array.isArray(def) && Array.isArray(value)) || + (def.constructor === Object && value.constructor === Object) + ) { + try { + return JSON.stringify(def) === JSON.stringify(value); + } + catch (e) { + } + } + } + return false; +} + +function flattenCodeArray (array, separator) { + var strList = []; + (function deepFlatten (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + if (Array.isArray(item)) { + deepFlatten(item); + } + else { + strList.push(item); + } + } + })(array); + return strList.join(separator); +} + +/* + * Variables: + * {Object[]} O - objs list + * {Function[]} F - constructor list + * {Node} [R] - specify an instantiated prefabRoot that all references to prefabRoot in prefab will redirect to + * {Object} o - current creating object + */ + +/* + * @param {Object} obj - the object to parse + * @param {Node} [parent] + */ +function Parser (obj, parent) { + this.parent = parent; + + this.objsToClear_iN$t = []; // used to reset _iN$t variable + this.codeArray = []; + + // datas for generated code + this.objs = []; + this.funcs = []; + + // {String[]} - variable names for circular references, + // not really global, just local variables shared between sub functions + this.globalVariables = []; + // incremental id for new global variables + this.globalVariableId = 0; + // incremental id for new local variables + this.localVariableId = 0; + + // generate codeArray + //if (Array.isArray(obj)) { + // this.codeArray.push(this.instantiateArray(obj)); + //} + //else { + this.codeArray.push(VAR + LOCAL_OBJ + ';', + 'if(R){', + LOCAL_OBJ + '=R;', + '}else{', + LOCAL_OBJ + '=R=' + NEW + this.getFuncModule(obj.constructor, true) + '();', + '}'); + obj._iN$t = { globalVar: 'R' }; + this.objsToClear_iN$t.push(obj); + this.enumerateObject(this.codeArray, obj); + //} + + // generate code + var globalVariablesDeclaration; + if (this.globalVariables.length > 0) { + globalVariablesDeclaration = VAR + this.globalVariables.join(',') + ';'; + } + var code = flattenCodeArray([SCOPE_START + '(O,F,R){', + globalVariablesDeclaration || [], + this.codeArray, + SCOPE_END], CC_DEV ? '\n' : ''); + + // generate method and bind with objs + var createFunction = eval(code); + this.result = createFunction.bind(null, this.objs, this.funcs); + + if (CC_TEST && !isPhantomJS) { + console.log(code); + } + + // cleanup + for (var i = 0, len = this.objsToClear_iN$t.length; i < len; ++i) { + this.objsToClear_iN$t[i]._iN$t = null; + } + this.objsToClear_iN$t.length = 0; +} + +JS.mixin(Parser.prototype, { + + getFuncModule: function (func, usedInNew) { + var clsName = JS.getClassName(func); + var clsNameIsModule = clsName.indexOf('.') !== -1; + if (clsNameIsModule) { + try { + // ensure is module + clsNameIsModule = (func === eval(clsName)); + if (clsNameIsModule) { + return clsName; + } + } + catch (e) {} + } + var index = this.funcs.indexOf(func); + if (index < 0) { + index = this.funcs.length; + this.funcs.push(func); + } + var res = 'F[' + index + ']'; + return usedInNew ? '(' + res + ')' : res; + }, + + getObjRef: function (obj) { + var index = this.objs.indexOf(obj); + if (index < 0) { + index = this.objs.length; + this.objs.push(obj); + } + return 'O[' + index + ']'; + }, + + enumerateCCClass: function (codeArray, obj, klass) { + var props = klass.__props__; + var attrs = Attr.getClassAttrs(klass); + for (var p = 0; p < props.length; p++) { + var key = props[p]; + if (CC_EDITOR && key === '_id') { + if (obj instanceof cc._BaseNode || obj instanceof cc.Component) { + continue; + } + } + if (attrs[key + SERIALIZABLE] !== false) { + var val = obj[key]; + if (equalsToDefault(attrs[key + DEFAULT], val)) { + continue; + } + this.writeField(codeArray, obj, key, val); + } + } + }, + + instantiateArray: function (value) { + if (value.length === 0) { + return '[]'; + } + + var arrayVar = 't' + (++this.localVariableId); + var codeArray = [arrayVar + '=new Array(' + value.length + ');']; + + // assign a _iN$t flag to indicate that this object has been parsed. + value._iN$t = { + globalVar: '', // the name of declared global variable used to access this object + source: codeArray, // the source code array for this object + }; + this.objsToClear_iN$t.push(value); + + for (var i = 0; i < value.length; ++i) { + var expression = this.enumerateField(value, i, value[i]); + if (Array.isArray(expression)) { + expression[0] = arrayVar + '[' + i + ']=' + expression[0]; + codeArray.push(expression); + } + else { + codeArray.push(arrayVar + '[' + i + ']=' + expression + ';'); + } + } + return codeArray; + }, + + enumerateField: function (obj, key, value) { + if (typeof value === 'object' && value) { + var _iN$t = value._iN$t; + if (_iN$t) { + // parsed + var globalVar = _iN$t.globalVar; + if (!globalVar) { + // declare a global var + globalVar = _iN$t.globalVar = 'v' + (++this.globalVariableId); + this.globalVariables.push(globalVar); + // insert assignment statement to assign to global var + var line = _iN$t.source[LINE_INDEX_OF_NEW_OBJ]; + if (line.startsWith(VAR)) { + // var o=xxx -> var o=global=xxx + var LEN_OF_VAR_O = 5; + _iN$t.source[LINE_INDEX_OF_NEW_OBJ] = line.slice(0, LEN_OF_VAR_O) + '=' + globalVar + line.slice(LEN_OF_VAR_O); + } + else { + _iN$t.source[LINE_INDEX_OF_NEW_OBJ] = globalVar + '=' + _iN$t.source[LINE_INDEX_OF_NEW_OBJ]; + } + } + return globalVar; + } + else if (Array.isArray(value)) { + return this.instantiateArray(value); + } + else { + return this.instantiateObj(value); + } + } + else if (typeof value === 'function') { + return this.getFuncModule(value); + } + else if (typeof value === 'string') { + return '"' + value + '"'; + } + else { + if (key === '_objFlags' && obj instanceof CCObject) { + value &= PersistentMask; + } + return value; + } + }, + + writeField: function (codeArray, obj, key, value) { + var statement; + if (NAME_IN_DOT_NOTATION_REG.test(key)) { + statement = LOCAL_OBJ + '.' + key + '='; + } + else { + statement = LOCAL_OBJ + '["' + key + '"]='; + } + var expression = this.enumerateField(obj, key, value); + if (Array.isArray(expression)) { + expression[0] = statement + expression[0]; + codeArray.push(expression); + } + else { + codeArray.push(statement + expression + ';'); + } + }, + + // codeArray - the source code array for this object + enumerateObject: function (codeArray, obj) { + var klass = obj.constructor; + if (cc.Class._isCCClass(klass)) { + this.enumerateCCClass(codeArray, obj, klass); + } + else { + // primitive javascript object + for (var key in obj) { + if (!obj.hasOwnProperty(key) || + (key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && // starts with "__" + key !== '__type__') + ) { + continue; + } + var value = obj[key]; + if (typeof value === 'object' && value && value === obj._iN$t) { + continue; + } + this.writeField(codeArray, obj, key, value); + } + } + }, + + instantiateObj: function (obj) { + if (obj instanceof cc.ValueType) { + return this.getNewValueTypeCode(obj); + } + if (obj instanceof cc.Asset) { + // register to asset list and just return the reference. + return this.getObjRef(obj); + } + if (obj._objFlags & Destroyed) { + // the same as cc.isValid(obj) + return null; + } + + var createCode; + var ctor = obj.constructor; + if (cc.Class._isCCClass(ctor)) { + if (this.parent) { + if (this.parent instanceof cc.Component) { + if (obj instanceof cc._BaseNode || obj instanceof cc.Component) { + return this.getObjRef(obj); + } + } + else if (this.parent instanceof cc._BaseNode) { + if (obj instanceof cc._BaseNode) { + if (!obj.isChildOf(this.parent)) { + // should not clone other nodes if not descendant + return this.getObjRef(obj); + } + } + else if (obj instanceof cc.Component) { + if (!obj.node.isChildOf(this.parent)) { + // should not clone other component if not descendant + return this.getObjRef(obj); + } + } + } + } + createCode = VAR + LOCAL_OBJ + '=' + NEW + this.getFuncModule(ctor, true) + '();'; + } + else if (ctor === Object) { + createCode = VAR + LOCAL_OBJ + '={};' + } + else { + // do not clone unknown type + return this.getObjRef(obj); + } + + var codeArray = [createCode]; + + // assign a _iN$t flag to indicate that this object has been parsed. + obj._iN$t = { + globalVar: '', // the name of declared global variable used to access this object + source: codeArray, // the source code array for this object + //propName: '', // the propName this object defined in its source code, + // // if defined, use LOCAL_OBJ.propName to access the obj, else just use o + }; + this.objsToClear_iN$t.push(obj); + + this.enumerateObject(codeArray, obj); + return [SCOPE_START + '(){', + codeArray, + SCOPE_END + '();']; + }, + + getNewValueTypeCode: function (value) { + var clsName = JS.getClassName(value); + var type = value.constructor; + var res = NEW + clsName + '('; + for (var i = 0; i < type.__props__.length; i++) { + var prop = type.__props__[i]; + var propVal = value[prop]; + if (typeof propVal === 'object') { + cc.error('Can not instantiate %s because it contains object property.', clsName); + return NEW + this.getFuncModule(value.constructor) + '();' + } + res += propVal; + if (i < type.__props__.length - 1) { + res += ',' + } + } + return res + ')'; + } +}); + + +function compile (node) { + var root = (node instanceof cc._BaseNode) && node; + var parser = new Parser(node, root); + return parser.result; +} + +module.exports = { + compile: compile, + equalsToDefault: equalsToDefault +}; + +if (CC_TEST) { + cc._Test.IntantiateJit = module.exports; +} diff --git a/cocos2d/core/utils/prefab-helper.js b/cocos2d/core/utils/prefab-helper.js index dba079e888..183eaf6920 100644 --- a/cocos2d/core/utils/prefab-helper.js +++ b/cocos2d/core/utils/prefab-helper.js @@ -84,16 +84,9 @@ module.exports = { var _localZOrder = node._localZOrder; var _globalZOrder = node._globalZOrder; - // root in prefab asset is always synced - var prefabRoot = _prefab.asset.data; - prefabRoot._prefab._synced = true; - - // use node as the instantiated prefabRoot to make references to prefabRoot in prefab redirect to node - prefabRoot._iN$t = node; - - // instantiate prefab and apply to node + // instantiate prefab cc.game._isCloning = true; - cc.instantiate._clone(prefabRoot, prefabRoot); + _prefab.asset._doInstantiate(node); cc.game._isCloning = false; // restore preserved props diff --git a/test/qunit/unit/test-instantiate.js b/test/qunit/unit/test-instantiate.js index 7bd1d32fd5..c7187a5565 100644 --- a/test/qunit/unit/test-instantiate.js +++ b/test/qunit/unit/test-instantiate.js @@ -1,17 +1,16 @@ -largeModule('Instantiate'); - -(function () { - var match = function (obj, expect, info) { - deepEqual(cc.instantiate(obj), expect, info); - }; + +function testInstantiate (module, match, instantiate) { + largeModule(module); test('basic', function () { match({}, {}, 'smoke test1'); + //match([], [], 'smoke test2'); match({ 1: 1, 2: [2, {3: '3'}]}, {1: 1, 2: [2, {3: '3'}]}, 'simple test1'); + //match([1], [1], 'simple test2'); var obj = {}; - var clone = cc.instantiate({ + var clone = instantiate({ ref1: obj, ref2: obj, }); @@ -57,7 +56,7 @@ var expect = new MyAsset(); expect.dynamicProp = false; - var clone = cc.instantiate(asset); + var clone = instantiate(asset); strictEqual(asset.constructor, clone.constructor, 'instantiated should has the same type'); deepEqual(clone, expect, 'can instantiate class'); @@ -69,13 +68,13 @@ var obj = new cc.Object(); obj._objFlags = cc.Object.Flags.EditorOnly; - var clone = cc.instantiate(obj); + var clone = instantiate(obj); strictEqual(clone._objFlags, cc.Object.Flags.EditorOnly, 'can clone obj flags'); //var hashObj = new cc.HashObject(); //var id = hashObj.id; // generate id - //var clonedHashObj = cc.instantiate(hashObj); + //var clonedHashObj = instantiate(hashObj); // //notEqual(clonedHashObj.id, id, 'should not clone id'); //notEqual(clonedHashObj.hashCode, hashObj.hashCode, 'should not clone hashCode'); @@ -102,7 +101,7 @@ sprite.size = new cc.Vec2(32, 2); sprite._isValid = false; - var clone = cc.instantiate(sprite); + var clone = instantiate(sprite); strictEqual(sprite.constructor, clone.constructor, 'instantiated should has the same type'); deepEqual(clone.size, new cc.Vec2(32, 2), 'can clone variable defined by property'); @@ -116,7 +115,7 @@ var obj = { pos: new cc.Vec2(1, 2) }; - var clone = cc.instantiate(obj); + var clone = instantiate(obj); ok(obj.pos !== clone.pos, 'value type should be cloned'); strictEqual(obj.pos.x, clone.pos.x, 'checking x'); @@ -135,7 +134,7 @@ this.dict2 = {num: 2, other: this.dict1}; this.dict1.other = this.dict2; } - var clone = cc.instantiate(new MyAsset()); + var clone = instantiate(new MyAsset()); deepEqual(new MyAsset(), clone, 'can instantiate'); strictEqual(clone.array1[1], clone.array2, 'two arrays can circular reference each other 1'); @@ -148,7 +147,7 @@ var sprite = {}; sprite.sprite = new cc.SpriteFrame(); - var clone = cc.instantiate(sprite); + var clone = instantiate(sprite); ok(sprite.sprite === clone.sprite, 'should not clone asset'); }); @@ -159,7 +158,7 @@ child.parent = node; cc.director.getScene().addChild(node); - var clone = cc.instantiate(node); + var clone = instantiate(node); ok(clone.parent === null, 'root of cloned node should not have parent'); ok(clone.children[0].parent === clone, 'cloned child node should have parent'); @@ -174,7 +173,7 @@ var node = new cc.Node(); node.addComponent(Script); - var clone = cc.instantiate(node); + var clone = instantiate(node); strictEqual(!!clone.getComponent(Script), true, 'should be added'); @@ -197,7 +196,7 @@ cc.Object._deferredDestroy(); - var clone = cc.instantiate(node); + var clone = instantiate(node); ok(clone.getComponent(Script).compRef === null, 'deleted object should be nullify'); }); @@ -242,7 +241,7 @@ childComp.nodeArrayInComp = [parent, other]; childComp.otherNodeInComp = other; - var cloneParent = cc.instantiate(parent); + var cloneParent = instantiate(parent); var cloneChild = cloneParent._children[0]; var cloneParentComp = cloneParent.getComponent(Script); var cloneChildComp = cloneChild.getComponent(Script); @@ -262,4 +261,27 @@ cc.js.unregisterClass(Script); }); -})(); +} +testInstantiate('Instantiate', + function (obj, expect, info) { + deepEqual(cc.instantiate(obj), expect, info); + }, + cc.instantiate +); +testInstantiate('Instantiate-JIT', + function (obj, expect, info) { + var createCode = new cc._Test.IntantiateJit.compile(obj); + var res = createCode(); + deepEqual(res, expect, info); + }, + function instantiate (obj) { + var createCode = new cc._Test.IntantiateJit.compile(obj); + cc.game._isCloning = true; + var cloned = createCode(); + if (obj._instantiate) { + obj._instantiate(cloned); + } + cc.game._isCloning = false; + return cloned; + } +); diff --git a/test/qunit/unit/test-prefab.js b/test/qunit/unit/test-prefab.js index a9be37aeef..dceefdd331 100644 --- a/test/qunit/unit/test-prefab.js +++ b/test/qunit/unit/test-prefab.js @@ -177,6 +177,10 @@ testNode.removeComponent(TestScript); testNode.children[1].parent = null; + var originParent = testNode.parent = new cc.Node(); + var outsideComp = originParent.addComponent(TestScript); + outsideComp.target = originParent; + testChild.x += 1; testChild.scale = cc.Vec2.ZERO; testChild.addComponent(TestScript); @@ -192,6 +196,8 @@ ok(testNode.x != prefab.data.x, 'Should not revert root position'); ok(testNode.getScaleX() === 123 && testNode.getScaleY() === 432, 'Revert property of the parent node'); ok(testNode.getComponent(TestScript).constructor === TestScript, 'Restore removed component'); + ok(testNode.parent === originParent, 'parent should not changed'); + ok(testNode.parent.getComponent(TestScript).target === originParent, 'component property of parent should not changed'); ok(testChild.x === prefab.data.children[0].x, 'Revert child position'); ok(testChild.getScaleX() === 22 && testChild.getScaleY() === 11, 'Revert child node'); @@ -209,7 +215,7 @@ comp.resetExpect(CallbackTester.OnLoad, 'call onLoad while attaching to node'); comp.pushExpect(CallbackTester.OnEnable, 'then call onEnable if node active'); - cc.director.getScene().addChild(testNode); + cc.director.getScene().addChild(testNode.parent); comp.stopTest(); From c61c9cfe3997d8b32b551c13bd956695b38519ac Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 4 Nov 2016 15:52:06 +0800 Subject: [PATCH 3/5] minor tweaks --- cocos2d/core/platform/CCClass.js | 9 ++++----- cocos2d/core/platform/instantiate-jit.js | 4 ++-- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 40f16e8e88..ff5cb1f3c1 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -280,9 +280,9 @@ function getDefault (defaultVal) { return defaultVal; } -var DELIMETER = Attr.DELIMETER; +var DEFAULT = Attr.DELIMETER + 'default'; function instantiateProps (instance, itsClass) { - var attrs = Attr.getClassAttrs(itsClass); + var attrs = itsClass.__attrs__ || Attr.getClassAttrs(itsClass); var propList = itsClass.__props__; if (propList === null) { deferredInitializer.init(); @@ -290,7 +290,7 @@ function instantiateProps (instance, itsClass) { } for (var i = 0; i < propList.length; i++) { var prop = propList[i]; - var attrKey = prop + DELIMETER + 'default'; + var attrKey = prop + DEFAULT; if (attrKey in attrs) { // getter does not have default var def = attrs[attrKey]; // default maybe 0 @@ -529,7 +529,7 @@ function _createCtor (ctor, baseClass, mixins, className, options) { } var superCallBounded = options && baseClass && boundSuperCalls(baseClass, options); - if (ctor && CC_DEV) { + if (CC_DEV && ctor) { _checkCtor(ctor, className); } // get base user constructors @@ -1091,7 +1091,6 @@ function parseAttributes (attrs, className, propName) { cc.Class = CCClass; module.exports = { - instantiateProps: instantiateProps, isArray: function (defaultVal) { defaultVal = getDefault(defaultVal); return Array.isArray(defaultVal); diff --git a/cocos2d/core/platform/instantiate-jit.js b/cocos2d/core/platform/instantiate-jit.js index 606e66ea0f..0838c9e957 100644 --- a/cocos2d/core/platform/instantiate-jit.js +++ b/cocos2d/core/platform/instantiate-jit.js @@ -398,11 +398,11 @@ JS.mixin(Parser.prototype, { var propVal = value[prop]; if (typeof propVal === 'object') { cc.error('Can not instantiate %s because it contains object property.', clsName); - return NEW + this.getFuncModule(value.constructor) + '();' + return NEW + this.getFuncModule(value.constructor) + '();'; } res += propVal; if (i < type.__props__.length - 1) { - res += ',' + res += ','; } } return res + ')'; From a2876a33f8ccf2d0fde23bf40d0bf0938416ddad Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 7 Nov 2016 15:57:28 +0800 Subject: [PATCH 4/5] bake CCClass property initializer (JIT) --- cocos2d/core/platform/CCClass.js | 147 ++++++++++++++++++++++--------- test/qunit/unit/test-class.js | 14 ++- 2 files changed, 119 insertions(+), 42 deletions(-) diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index ff5cb1f3c1..bfa7871655 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -280,41 +280,6 @@ function getDefault (defaultVal) { return defaultVal; } -var DEFAULT = Attr.DELIMETER + 'default'; -function instantiateProps (instance, itsClass) { - var attrs = itsClass.__attrs__ || Attr.getClassAttrs(itsClass); - var propList = itsClass.__props__; - if (propList === null) { - deferredInitializer.init(); - propList = itsClass.__props__; - } - for (var i = 0; i < propList.length; i++) { - var prop = propList[i]; - var attrKey = prop + DEFAULT; - if (attrKey in attrs) { // getter does not have default - var def = attrs[attrKey]; - // default maybe 0 - if (def) { - if (typeof def === 'object' && def) { - if (typeof def.clone === 'function') { - def = def.clone(); - } - else if (Array.isArray(def)) { - def = []; - } - else { - def = {}; - } - } - else if (typeof def === 'function') { - def = getDefault(def); - } - } - instance[prop] = def; - } - } -} - /** * Checks whether subclass is child of superclass or equals to superclass * @@ -417,6 +382,8 @@ function doDefine (className, baseClass, mixins, constructor, options) { fireClass.prototype.constructor = fireClass; } + fireClass.prototype.__initProps__ = compileProps; + JS.setClassName(className, fireClass); return fireClass; } @@ -506,6 +473,106 @@ function normalizeClassName (className) { } } +var NAME_IN_DOT_NOTATION_REG = /^[$A-Za-z_][0-9A-Za-z_$]*$/; +var DEFAULT = Attr.DELIMETER + 'default'; +var NEW = 'new '; +function getNewValueTypeCode (value) { + var clsName = JS.getClassName(value); + var type = value.constructor; + var res = NEW + clsName + '('; + for (var i = 0; i < type.__props__.length; i++) { + var prop = type.__props__[i]; + var propVal = value[prop]; + if (typeof propVal === 'object') { + cc.error('Can not construct %s because it contains object property.', clsName); + return NEW + clsName + '()'; + } + res += propVal; + if (i < type.__props__.length - 1) { + res += ',' + } + } + return res + ')'; +} + +function compileProps (actualClass) { + var attrs = Attr.getClassAttrs(actualClass); + var propList = actualClass.__props__; + if (propList === null) { + deferredInitializer.init(); + propList = actualClass.__props__; + } + + // functions for generated code + var F = []; + + var func = '(function(){\n'; + + for (var i = 0; i < propList.length; i++) { + var prop = propList[i]; + var attrKey = prop + DEFAULT; + if (attrKey in attrs) { // getter does not have default + var statement; + if (NAME_IN_DOT_NOTATION_REG.test(prop)) { + statement = 'this.' + prop + '='; + } + else { + statement = 'this["' + prop + '"]='; + } + var expression; + var def = attrs[attrKey]; + if (typeof def === 'object' && def) { + if (def instanceof cc.ValueType) { + expression = getNewValueTypeCode(def); + } + else if (Array.isArray(def)) { + expression = '[]'; + } + else { + expression = '{}'; + } + } + else if (typeof def === 'function') { + var index = F.length; + F.push(def); + expression = 'F[' + index + ']()'; + if (CC_EDITOR) { + func += 'try {\n' + statement + expression + ';\n}\ncatch(e) {\ncc._throw(e);\n' + statement + 'undefined;\n}\n'; + continue; + } + } + else if (typeof def === 'string') { + expression = '"' + def + '"'; + } + else { + // number, boolean, null, undefined + expression = def; + } + statement = statement + expression + ';\n'; + func += statement; + } + } + + func += '})'; + + if (CC_TEST && !isPhantomJS) { + console.log(func); + } + + // jshint evil: true + var instantiateProps = (function (F) { + // wrap a new scope to enalbe minify + return eval(func); + })(F); + // jshint evil: false + + // overwite __initProps__ to avoid compile again + actualClass.prototype.__initProps__ = instantiateProps; + + // immediate call instantiateProps, no need actualClass anymore + this.__initProps__(); +} + function _createCtor (ctor, baseClass, mixins, className, options) { var useTryCatch = ! (className && className.startsWith('cc.')); var shouldAddProtoCtor; @@ -566,7 +633,9 @@ function _createCtor (ctor, baseClass, mixins, className, options) { if (superCallBounded) { body += 'this._super=null;\n'; } - body += 'instantiateProps(this,fireClass);\n'; + + // instantiate props + body += 'this.__initProps__(fireClass);\n'; // call user constructors if (ctors.length > 0) { @@ -778,11 +847,7 @@ function declareProperties (cls, className, properties, baseClass, mixins) { }; */ function CCClass (options) { - if (arguments.length === 0) { - return define(); - } - if ( !options ) { - cc.error('cc.Class: Option must be non-nil'); + if (!options) { return define(); } diff --git a/test/qunit/unit/test-class.js b/test/qunit/unit/test-class.js index 9966c10064..7c3086db86 100644 --- a/test/qunit/unit/test-class.js +++ b/test/qunit/unit/test-class.js @@ -268,11 +268,17 @@ test('prop initial times', function () { }); var fooTester = Callback().enable(); var instanceMocker = { - ctor: Base, // mock constructor of class instance + ctor: Base, // mock constructor of class instance, }; Object.defineProperty(instanceMocker, 'foo', { set: fooTester }); + Object.defineProperty(instanceMocker, '__initProps__', { + get: function () { + return Base.prototype.__initProps__; + }, + configurable: true + }); Base.call(instanceMocker); fooTester.once('property should init once'); @@ -287,6 +293,12 @@ test('prop initial times', function () { Object.defineProperty(instanceMocker, 'bar', { set: barTester }); + Object.defineProperty(instanceMocker, '__initProps__', { + get: function () { + return Sub.prototype.__initProps__; + }, + configurable: true + }); Sub.call(instanceMocker); fooTester.once('foo prop should init once even if inherited'); barTester.once('bar prop should init once'); From faaa9128a76a98320f013805df5955d0f74be649 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 7 Nov 2016 16:16:50 +0800 Subject: [PATCH 5/5] wrap eval to a new scope to perfect minify --- cocos2d/core/platform/CCClass.js | 44 ++++++++++++++---------- cocos2d/core/platform/instantiate-jit.js | 40 ++++++++------------- 2 files changed, 40 insertions(+), 44 deletions(-) diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index bfa7871655..5004cded08 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -473,19 +473,16 @@ function normalizeClassName (className) { } } -var NAME_IN_DOT_NOTATION_REG = /^[$A-Za-z_][0-9A-Za-z_$]*$/; -var DEFAULT = Attr.DELIMETER + 'default'; -var NEW = 'new '; function getNewValueTypeCode (value) { var clsName = JS.getClassName(value); var type = value.constructor; - var res = NEW + clsName + '('; + var res = 'new ' + clsName + '('; for (var i = 0; i < type.__props__.length; i++) { var prop = type.__props__[i]; var propVal = value[prop]; if (typeof propVal === 'object') { cc.error('Can not construct %s because it contains object property.', clsName); - return NEW + clsName + '()'; + return 'new ' + clsName + '()'; } res += propVal; if (i < type.__props__.length - 1) { @@ -495,7 +492,16 @@ function getNewValueTypeCode (value) { return res + ')'; } +// wrap a new scope to enalbe minify +function cleanEval_F (code, F) { + // jshint evil: true + return eval(code); + // jshint evil: false +} + +var NAME_IN_DOT_NOTATION_REG = /^[$A-Za-z_][0-9A-Za-z_$]*$/; function compileProps (actualClass) { + // init deferred properties var attrs = Attr.getClassAttrs(actualClass); var propList = actualClass.__props__; if (propList === null) { @@ -505,12 +511,11 @@ function compileProps (actualClass) { // functions for generated code var F = []; - var func = '(function(){\n'; for (var i = 0; i < propList.length; i++) { var prop = propList[i]; - var attrKey = prop + DEFAULT; + var attrKey = prop + Attr.DELIMETER + 'default'; if (attrKey in attrs) { // getter does not have default var statement; if (NAME_IN_DOT_NOTATION_REG.test(prop)) { @@ -559,20 +564,21 @@ function compileProps (actualClass) { console.log(func); } - // jshint evil: true - var instantiateProps = (function (F) { - // wrap a new scope to enalbe minify - return eval(func); - })(F); - // jshint evil: false - // overwite __initProps__ to avoid compile again - actualClass.prototype.__initProps__ = instantiateProps; + actualClass.prototype.__initProps__ = cleanEval_F(func, F); - // immediate call instantiateProps, no need actualClass anymore + // call instantiateProps immediately, no need to pass actualClass into it anymore this.__initProps__(); } +// wrap a new scope to enalbe minify +function cleanEval_fireClass (code) { + // jshint evil: true + var fireClass = eval(code); + // jshint evil: false + return fireClass; +} + function _createCtor (ctor, baseClass, mixins, className, options) { var useTryCatch = ! (className && className.startsWith('cc.')); var shouldAddProtoCtor; @@ -662,7 +668,7 @@ function _createCtor (ctor, baseClass, mixins, className, options) { body += '})'; // jshint evil: true - var fireClass = eval(body); + var fireClass = cleanEval_fireClass(body); // jshint evil: false Object.defineProperty(fireClass, '__ctors__', { @@ -1160,7 +1166,9 @@ module.exports = { defaultVal = getDefault(defaultVal); return Array.isArray(defaultVal); }, - fastDefine: CCClass._fastDefine + fastDefine: CCClass._fastDefine, + getNewValueTypeCode: getNewValueTypeCode, + NAME_IN_DOT_NOTATION_REG: NAME_IN_DOT_NOTATION_REG, }; if (CC_EDITOR) { diff --git a/cocos2d/core/platform/instantiate-jit.js b/cocos2d/core/platform/instantiate-jit.js index 0838c9e957..b34ee81907 100644 --- a/cocos2d/core/platform/instantiate-jit.js +++ b/cocos2d/core/platform/instantiate-jit.js @@ -30,14 +30,14 @@ var Destroyed = CCObject.Flags.Destroyed; var PersistentMask = CCObject.Flags.PersistentMask; var Attr = require('./attribute'); var JS = require('./js'); +var CCClass = require('./CCClass'); var SERIALIZABLE = Attr.DELIMETER + 'serializable'; var DEFAULT = Attr.DELIMETER + 'default'; +var NAME_IN_DOT_NOTATION_REG = CCClass.NAME_IN_DOT_NOTATION_REG; -var NAME_IN_DOT_NOTATION_REG = /^[$A-Za-z_][0-9A-Za-z_$]*$/; var VAR = 'var '; var LOCAL_OBJ = 'o'; -var NEW = 'new '; var SCOPE_START = '(function'; var SCOPE_END = 'return o;})'; var LINE_INDEX_OF_NEW_OBJ = 0; @@ -87,6 +87,13 @@ function flattenCodeArray (array, separator) { return strList.join(separator); } +// wrap a new scope to enalbe minify +function cleanEval (code) { + // jshint evil: true + return eval(code); + // jshint evil: false +} + /* * Variables: * {Object[]} O - objs list @@ -126,7 +133,7 @@ function Parser (obj, parent) { 'if(R){', LOCAL_OBJ + '=R;', '}else{', - LOCAL_OBJ + '=R=' + NEW + this.getFuncModule(obj.constructor, true) + '();', + LOCAL_OBJ + '=R=new ' + this.getFuncModule(obj.constructor, true) + '();', '}'); obj._iN$t = { globalVar: 'R' }; this.objsToClear_iN$t.push(obj); @@ -144,7 +151,7 @@ function Parser (obj, parent) { SCOPE_END], CC_DEV ? '\n' : ''); // generate method and bind with objs - var createFunction = eval(code); + var createFunction = cleanEval(code); this.result = createFunction.bind(null, this.objs, this.funcs); if (CC_TEST && !isPhantomJS) { @@ -166,7 +173,7 @@ JS.mixin(Parser.prototype, { if (clsNameIsModule) { try { // ensure is module - clsNameIsModule = (func === eval(clsName)); + clsNameIsModule = (func === cleanEval(clsName)); if (clsNameIsModule) { return clsName; } @@ -327,7 +334,7 @@ JS.mixin(Parser.prototype, { instantiateObj: function (obj) { if (obj instanceof cc.ValueType) { - return this.getNewValueTypeCode(obj); + return CCClass.getNewValueTypeCode(obj); } if (obj instanceof cc.Asset) { // register to asset list and just return the reference. @@ -362,7 +369,7 @@ JS.mixin(Parser.prototype, { } } } - createCode = VAR + LOCAL_OBJ + '=' + NEW + this.getFuncModule(ctor, true) + '();'; + createCode = VAR + LOCAL_OBJ + '=new ' + this.getFuncModule(ctor, true) + '();'; } else if (ctor === Object) { createCode = VAR + LOCAL_OBJ + '={};' @@ -388,25 +395,6 @@ JS.mixin(Parser.prototype, { codeArray, SCOPE_END + '();']; }, - - getNewValueTypeCode: function (value) { - var clsName = JS.getClassName(value); - var type = value.constructor; - var res = NEW + clsName + '('; - for (var i = 0; i < type.__props__.length; i++) { - var prop = type.__props__[i]; - var propVal = value[prop]; - if (typeof propVal === 'object') { - cc.error('Can not instantiate %s because it contains object property.', clsName); - return NEW + this.getFuncModule(value.constructor) + '();'; - } - res += propVal; - if (i < type.__props__.length - 1) { - res += ','; - } - } - return res + ')'; - } });