From d2e4116546830bb185679af99a5cce6d590403a4 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 24 Nov 2016 17:06:52 +0800 Subject: [PATCH 1/2] move runtime eval to misc.js to enalbe mangle in other souces --- cocos2d/core/platform/CCClass.js | 28 ++++++----------------- cocos2d/core/platform/instantiate-jit.js | 8 +------ cocos2d/core/utils/misc.js | 29 +++++++++++++++++++----- 3 files changed, 31 insertions(+), 34 deletions(-) diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 7659e6dfa8..930bf5a86e 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -31,6 +31,7 @@ var _cloneable_DEV = Utils.cloneable_DEV; var Attr = require('./attribute'); var getTypeChecker = Attr.getTypeChecker; var preprocessAttrs = require('./preprocess-attrs'); +var Misc = require('../utils/misc'); var BUILTIN_ENTRIES = ['name', 'extends', 'mixins', 'ctor', 'properties', 'statics', 'editor']; @@ -401,19 +402,12 @@ function getNewValueTypeCode (value) { } res += propVal; if (i < type.__props__.length - 1) { - res += ',' + res += ','; } } return res + ')'; } -// wrap a new scope to enalbe minify -function cleanEval_F (code, F) { - // jshint evil: true - return eval(code); - // jshint evil: false -} - // convert a normal string including newlines, quotes and unicode characters into a string literal // ready to use in JavaScript source function escapeForJS (s) { @@ -485,25 +479,17 @@ function compileProps (actualClass) { func += '})'; - if (CC_TEST && !isPhantomJS) { - console.log(func); - } + // if (CC_TEST && !isPhantomJS) { + // console.log(func); + // } // overwite __initProps__ to avoid compile again - actualClass.prototype.__initProps__ = cleanEval_F(func, F); + actualClass.prototype.__initProps__ = Misc.cleanEval_F(func, F); // 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; @@ -611,7 +597,7 @@ function _createCtor (ctor, baseClass, mixins, className, options) { body += '})'; // jshint evil: true - var fireClass = cleanEval_fireClass(body); + var fireClass = Misc.cleanEval_fireClass(body); // jshint evil: false Object.defineProperty(fireClass, '__ctors__', { diff --git a/cocos2d/core/platform/instantiate-jit.js b/cocos2d/core/platform/instantiate-jit.js index 0e00f6e05b..9b8bcc239d 100644 --- a/cocos2d/core/platform/instantiate-jit.js +++ b/cocos2d/core/platform/instantiate-jit.js @@ -30,6 +30,7 @@ var Destroyed = CCObject.Flags.Destroyed; var PersistentMask = CCObject.Flags.PersistentMask; var Attr = require('./attribute'); var JS = require('./js'); +var cleanEval = require('../utils/misc').cleanEval; var CCClass = require('./CCClass'); var SERIALIZABLE = Attr.DELIMETER + 'serializable'; @@ -86,13 +87,6 @@ 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 diff --git a/cocos2d/core/utils/misc.js b/cocos2d/core/utils/misc.js index 4fc2160ff8..3f2fce8257 100644 --- a/cocos2d/core/utils/misc.js +++ b/cocos2d/core/utils/misc.js @@ -23,9 +23,10 @@ THE SOFTWARE. ****************************************************************************/ -var misc = {}; +// should not use long variable name because eval breaks uglify's mangle operation in this file +var m = {}; -misc.propertyDefine = function (ctor, sameNameGetSets, diffNameGetSets) { +m.propertyDefine = function (ctor, sameNameGetSets, diffNameGetSets) { function define (np, propName, getter, setter) { var pd = Object.getOwnPropertyDescriptor(np, propName); if (pd) { @@ -62,7 +63,7 @@ misc.propertyDefine = function (ctor, sameNameGetSets, diffNameGetSets) { * @return {Number} * Constructor */ -misc.NextPOT = function (x) { +m.NextPOT = function (x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); @@ -72,7 +73,7 @@ misc.NextPOT = function (x) { return x + 1; }; -//var DirtyFlags = misc.DirtyFlags = { +//var DirtyFlags = m.DirtyFlags = { // TRANSFORM: 1 << 0, // SIZE: 1 << 1, // //Visible: @@ -87,7 +88,7 @@ misc.NextPOT = function (x) { // //DirtyFlags.WIDGET = DirtyFlags.TRANSFORM | DirtyFlags.SIZE; -misc.destructIgnoreId = function () { +m.destructIgnoreId = function () { // The same as Object._destruct but dont reset _id when destroyed for (var key in this) { if (this.hasOwnProperty(key) && key !== '_id') { @@ -104,4 +105,20 @@ misc.destructIgnoreId = function () { } }; -module.exports = misc; +// wrap a new scope to enalbe minify + +// jshint evil: true +m.cleanEval = function (code) { + return eval(code); +}; +m.cleanEval_F = function (code, F) { + return eval(code); +}; +m.cleanEval_fireClass = function (code) { + var fireClass = eval(code); + return fireClass; +}; +// jshint evil: false + + +module.exports = m; From 5dc7735e0d52178aaf598c1414b58074a99637a6 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 24 Nov 2016 18:21:34 +0800 Subject: [PATCH 2/2] optimize destruct operation by using eval --- cocos2d/core/components/CCComponent.js | 2 - cocos2d/core/load-pipeline/CCLoader.js | 2 +- cocos2d/core/platform/CCObject.js | 154 ++++++++++++++++++------- cocos2d/core/platform/utils.js | 2 + cocos2d/core/utils/base-node.js | 2 - cocos2d/core/utils/misc.js | 17 --- test/qunit/unit/test-object.js | 24 ++++ 7 files changed, 137 insertions(+), 66 deletions(-) diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index fe6070984d..66424fb150 100644 --- a/cocos2d/core/components/CCComponent.js +++ b/cocos2d/core/components/CCComponent.js @@ -749,8 +749,6 @@ var Component = cc.Class({ } }, - _destruct: Misc.destructIgnoreId, - _instantiate: function (cloned) { if (!cloned) { cloned = cc.instantiate._clone(this, this); diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index 6e2883fa8c..139809adcc 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -516,7 +516,7 @@ JS.mixin(CCLoader.prototype, { * 通过 id(通常是资源 url)来释放一个资源或者一个资源数组。 * 从 v1.3 开始,这个方法不仅会从 loader 中删除资源的缓存引用,还会清理它的资源内容。 * 比如说,当你释放一个 texture 资源,这个 texture 和它的 gl 贴图数据都会被释放。 - * 在复杂项目中,我们建议你结合 {{#crossLink "loader/getDependsRecursively:method"}}{{/crossLink}} 来使用,便于在设备内存告急的情况下更快得释放不再需要的资源的内存。 + * 在复杂项目中,我们建议你结合 {{#crossLink "loader/getDependsRecursively:method"}}{{/crossLink}} 来使用,便于在设备内存告急的情况下更快地释放不再需要的资源的内存。 * 注意,这个函数可能会导致资源贴图或资源所依赖的贴图不可用,如果场景中存在节点仍然依赖同样的贴图,它们可能会变黑并报 GL 错误。 * 如果你只想删除一个资源的缓存引用,请使用 {{#crossLink "pipeline/removeItem:method"}}{{/crossLink}} * diff --git a/cocos2d/core/platform/CCObject.js b/cocos2d/core/platform/CCObject.js index 1b8dee79e7..ddc0880701 100644 --- a/cocos2d/core/platform/CCObject.js +++ b/cocos2d/core/platform/CCObject.js @@ -1,4 +1,6 @@ var JS = require('./js'); +var CCClass = require('./CCClass'); +var cleanEval = require('../utils/misc').cleanEval; // definitions for CCObject.Flags @@ -34,8 +36,6 @@ var PersistentMask = ~(ToDestroy | Dirty | Destroying | DontDestroy | Activating IsOnEnableCalled | IsEditorOnEnableCalled | IsRotationLocked | IsScaleLocked | IsAnchorLocked | IsSizeLocked | IsPositionLocked /*RegisteredInEditor*/); -// TODO -//var PersistentMask = Destroyed | RealDestroyed | DontSave | EditorOnly; /** * The base class of most of all the objects in Fireball. @@ -59,6 +59,15 @@ function CCObject () { */ this._objFlags = 0; } +CCClass.fastDefine('cc.Object', CCObject, { _name: '', _objFlags: 0 }); + +function defineNotInheritable (obj, prop, value, writable) { + Object.defineProperty(obj, prop, { + value: value, + writable: !!writable + // enumerable is false by default + }); +} /** * Bit mask that controls object states. @@ -66,7 +75,7 @@ function CCObject () { * @static * @private */ -CCObject.Flags = { +defineNotInheritable(CCObject, 'Flags', { Destroyed: Destroyed, //ToDestroy: ToDestroy, @@ -150,11 +159,7 @@ CCObject.Flags = { IsScaleLocked: IsScaleLocked, IsAnchorLocked: IsAnchorLocked, IsSizeLocked: IsSizeLocked, -}; - -require('./CCClass').fastDefine('cc.Object', CCObject, { _name: '', _objFlags: 0 }); - -// internal static +}); var objectsToDestroy = []; @@ -180,18 +185,13 @@ function deferredDestroy () { } } -Object.defineProperty(CCObject, '_deferredDestroy', { - value: deferredDestroy, - // enumerable is false by default -}); +defineNotInheritable(CCObject, '_deferredDestroy', deferredDestroy); if (CC_EDITOR) { - Object.defineProperty(CCObject, '_clearDeferredDestroyTimer', { - value: function () { - if (deferredDestroyTimer !== null) { - clearImmediate(deferredDestroyTimer); - deferredDestroyTimer = null; - } + defineNotInheritable(CCObject, '_clearDeferredDestroyTimer', function () { + if (deferredDestroyTimer !== null) { + clearImmediate(deferredDestroyTimer); + deferredDestroyTimer = null; } }); } @@ -301,29 +301,100 @@ if (CC_EDITOR || CC_TEST) { }; } -/** - * Clear all references in the instance. - * - * NOTE: this method will not clear the getter or setter functions which defined in the INSTANCE of CCObject. - * You can override the _destruct method if you need. - * @method _destruct - * @private - */ -prototype._destruct = function () { - // 所有可枚举到的属性,都会被清空 - for (var key in this) { - if (this.hasOwnProperty(key)) { - switch (typeof this[key]) { +function compileDestruct (obj, ctor) { + var key, propsToReset = {}; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + switch (typeof obj[key]) { case 'string': - this[key] = ''; + propsToReset[key] = ''; break; case 'object': case 'function': - this[key] = null; + propsToReset[key] = null; break; } } } + // Overwrite propsToReset according to Class + if (cc.Class._isCCClass(ctor)) { + var attrs = cc.Class.Attr.getClassAttrs(ctor); + var propList = ctor.__props__; + for (var i = 0; i < propList.length; i++) { + key = propList[i]; + var attrKey = key + cc.Class.Attr.DELIMETER + 'default'; + if (attrKey in attrs) { + switch (typeof attrs[attrKey]) { + case 'string': + propsToReset[key] = ''; + break; + case 'object': + case 'function': + propsToReset[key] = null; + break; + case 'undefined': + propsToReset[key] = undefined; + break; + } + } + } + } + // compile code + var skipId = obj instanceof cc._BaseNode || obj instanceof cc.Component; + var func = '(function(o){\n'; + for (key in propsToReset) { + if (skipId && key === '_id') { + continue; + } + var statement; + if (CCClass.VAR_REG.test(key)) { + statement = 'o.' + key + '='; + } + else { + statement = 'o[' + CCClass.escapeForJS(key) + ']='; + } + var val = propsToReset[key]; + if (val === '') { + val = '""'; + } + func += (statement + val + ';\n'); + } + func += '})'; + + return cleanEval(func); +} + +/** + * Clear all references in the instance. + * + * NOTE: this method will not clear the getter or setter functions which defined in the instance of CCObject. + * You can override the _destruct method if you need, for example: + * _destruct: function () { + * for (var key in this) { + * if (this.hasOwnProperty(key)) { + * switch (typeof this[key]) { + * case 'string': + * this[key] = ''; + * break; + * case 'object': + * case 'function': + * this[key] = null; + * break; + * } + * } + * } + * + * @method _destruct + * @private + */ +prototype._destruct = function () { + var ctor = this.constructor; + var destruct = ctor.__destruct__; + if (!destruct) { + destruct = compileDestruct(this, ctor); + defineNotInheritable(ctor, '__destruct__', destruct, true); + } + destruct(this); }; /** @@ -393,18 +464,13 @@ cc.isValid = function (value) { }; if (CC_EDITOR || CC_TEST) { - Object.defineProperty(CCObject, '_willDestroy', { - value: function (obj) { - return !(obj._objFlags & Destroyed) && (obj._objFlags & ToDestroy) > 0; - } + defineNotInheritable(CCObject, '_willDestroy', function (obj) { + return !(obj._objFlags & Destroyed) && (obj._objFlags & ToDestroy) > 0; }); - Object.defineProperty(CCObject, '_cancelDestroy', { - value: function (obj) { - obj._objFlags &= ~ToDestroy; - JS.array.fastRemove(objectsToDestroy, obj); - } + defineNotInheritable(CCObject, '_cancelDestroy', function (obj) { + obj._objFlags &= ~ToDestroy; + JS.array.fastRemove(objectsToDestroy, obj); }); } -cc.Object = CCObject; -module.exports = CCObject; +cc.Object = module.exports = CCObject; diff --git a/cocos2d/core/platform/utils.js b/cocos2d/core/platform/utils.js index 64d028388e..c00d35095e 100644 --- a/cocos2d/core/platform/utils.js +++ b/cocos2d/core/platform/utils.js @@ -23,6 +23,8 @@ THE SOFTWARE. ****************************************************************************/ +// TODO - merge with misc.js + module.exports = { isDomNode: typeof window === 'object' && (typeof Node === 'function' ? function (obj) { diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index e6a201c584..dabe8aaef0 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -802,8 +802,6 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ } }, - _destruct: Misc.destructIgnoreId, - // ABSTRACT INTERFACES // called when the node's parent changed diff --git a/cocos2d/core/utils/misc.js b/cocos2d/core/utils/misc.js index 3f2fce8257..21ccfb07d2 100644 --- a/cocos2d/core/utils/misc.js +++ b/cocos2d/core/utils/misc.js @@ -88,23 +88,6 @@ m.NextPOT = function (x) { // //DirtyFlags.WIDGET = DirtyFlags.TRANSFORM | DirtyFlags.SIZE; -m.destructIgnoreId = function () { - // The same as Object._destruct but dont reset _id when destroyed - for (var key in this) { - if (this.hasOwnProperty(key) && key !== '_id') { - switch (typeof this[key]) { - case 'string': - this[key] = ''; - break; - case 'object': - case 'function': - this[key] = null; - break; - } - } - } -}; - // wrap a new scope to enalbe minify // jshint evil: true diff --git a/test/qunit/unit/test-object.js b/test/qunit/unit/test-object.js index 41eb98719c..0c3194c064 100644 --- a/test/qunit/unit/test-object.js +++ b/test/qunit/unit/test-object.js @@ -152,6 +152,8 @@ test('destroy other at destroy callback', 3, function () { }); test('destruct', function () { + CCObject.__destruct__ = null; // allow to parse dynamic properties + var obj1 = new CCObject(); // add dynamic value to instance @@ -187,4 +189,26 @@ test('destruct', function () { !inherited1.function_value, 'should remove instance value'); ok(inherited1._destruct, 'will not effect prototype method'); ok(inherited2.array, 'should not effect other instance value'); + + // CCClass test + var Class = cc.Class({ + extends: CCObject, + ctor: function () { + this.dynamicProp = null; + }, + properties: { + object_value_by_default: null + } + }); + var previousObj = new Class(); + previousObj.object_value_by_default = true; // change to boolean + previousObj._destroyImmediate(); + + var newObj = new Class(); + newObj.object_value_by_default = []; + newObj.dynamicProp = []; + newObj._destroyImmediate(); + + ok(!newObj.object_value_by_default , 'should always reset properties event if type changed on-the-fly'); + ok(!newObj.dynamicProp , 'should remove instance value even if defined in ctor'); });