CCClass.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /****************************************************************************
  2. Copyright (c) 2008-2010 Ricardo Quesada
  3. Copyright (c) 2011-2012 cocos2d-x.org
  4. Copyright (c) 2013-2014 Chukong Technologies Inc.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. ****************************************************************************/
  22. /**
  23. * The main namespace of Cocos2d-JS, all engine core classes, functions, properties and constants are defined in this namespace
  24. * @namespace
  25. * @name cc
  26. */
  27. var cc = cc || {};
  28. /**
  29. * @namespace
  30. * @name ClassManager
  31. */
  32. var ClassManager = {
  33. id : (0|(Math.random()*998)),
  34. instanceId : (0|(Math.random()*998)),
  35. compileSuper : function(func, name, id){
  36. //make the func to a string
  37. var str = func.toString();
  38. //find parameters
  39. var pstart = str.indexOf('('), pend = str.indexOf(')');
  40. var params = str.substring(pstart+1, pend);
  41. params = params.trim();
  42. //find function body
  43. var bstart = str.indexOf('{'), bend = str.lastIndexOf('}');
  44. var str = str.substring(bstart+1, bend);
  45. //now we have the content of the function, replace this._super
  46. //find this._super
  47. while(str.indexOf('this._super')!= -1)
  48. {
  49. var sp = str.indexOf('this._super');
  50. //find the first '(' from this._super)
  51. var bp = str.indexOf('(', sp);
  52. //find if we are passing params to super
  53. var bbp = str.indexOf(')', bp);
  54. var superParams = str.substring(bp+1, bbp);
  55. superParams = superParams.trim();
  56. var coma = superParams? ',':'';
  57. //replace this._super
  58. str = str.substring(0, sp)+ 'ClassManager['+id+'].'+name+'.call(this'+coma+str.substring(bp+1);
  59. }
  60. return Function(params, str);
  61. },
  62. getNewID : function(){
  63. return this.id++;
  64. },
  65. getNewInstanceId : function(){
  66. return this.instanceId++;
  67. }
  68. };
  69. ClassManager.compileSuper.ClassManager = ClassManager;
  70. /* Managed JavaScript Inheritance
  71. * Based on John Resig's Simple JavaScript Inheritance http://ejohn.org/blog/simple-javascript-inheritance/
  72. * MIT Licensed.
  73. */
  74. (function () {
  75. var fnTest = /\b_super\b/;
  76. var config = cc.game.config;
  77. var releaseMode = config[cc.game.CONFIG_KEY.classReleaseMode];
  78. if(releaseMode) {
  79. console.log("release Mode");
  80. }
  81. /**
  82. * The base Class implementation (does nothing)
  83. * @class
  84. */
  85. cc.Class = function () {
  86. };
  87. /**
  88. * Create a new Class that inherits from this Class
  89. * @static
  90. * @param {object} props
  91. * @return {function}
  92. */
  93. cc.Class.extend = function (props) {
  94. var _super = this.prototype;
  95. // Instantiate a base Class (but only create the instance,
  96. // don't run the init constructor)
  97. var prototype = Object.create(_super);
  98. var classId = ClassManager.getNewID();
  99. ClassManager[classId] = _super;
  100. // Copy the properties over onto the new prototype. We make function
  101. // properties non-eumerable as this makes typeof === 'function' check
  102. // unneccessary in the for...in loop used 1) for generating Class()
  103. // 2) for cc.clone and perhaps more. It is also required to make
  104. // these function properties cacheable in Carakan.
  105. var desc = { writable: true, enumerable: false, configurable: true };
  106. prototype.__instanceId = null;
  107. // The dummy Class constructor
  108. function Class() {
  109. this.__instanceId = ClassManager.getNewInstanceId();
  110. // All construction is actually done in the init method
  111. if (this.ctor)
  112. this.ctor.apply(this, arguments);
  113. }
  114. Class.id = classId;
  115. // desc = { writable: true, enumerable: false, configurable: true,
  116. // value: XXX }; Again, we make this non-enumerable.
  117. desc.value = classId;
  118. Object.defineProperty(prototype, '__pid', desc);
  119. // Populate our constructed prototype object
  120. Class.prototype = prototype;
  121. // Enforce the constructor to be what we expect
  122. desc.value = Class;
  123. Object.defineProperty(Class.prototype, 'constructor', desc);
  124. // Copy getter/setter
  125. this.__getters__ && (Class.__getters__ = cc.clone(this.__getters__));
  126. this.__setters__ && (Class.__setters__ = cc.clone(this.__setters__));
  127. for(var idx = 0, li = arguments.length; idx < li; ++idx) {
  128. var prop = arguments[idx];
  129. for (var name in prop) {
  130. var isFunc = (typeof prop[name] === "function");
  131. var override = (typeof _super[name] === "function");
  132. var hasSuperCall = fnTest.test(prop[name]);
  133. if (releaseMode && isFunc && override && hasSuperCall) {
  134. desc.value = ClassManager.compileSuper(prop[name], name, classId);
  135. Object.defineProperty(prototype, name, desc);
  136. } else if (isFunc && override && hasSuperCall) {
  137. desc.value = (function (name, fn) {
  138. return function () {
  139. var tmp = this._super;
  140. // Add a new ._super() method that is the same method
  141. // but on the super-Class
  142. this._super = _super[name];
  143. // The method only need to be bound temporarily, so we
  144. // remove it when we're done executing
  145. var ret = fn.apply(this, arguments);
  146. this._super = tmp;
  147. return ret;
  148. };
  149. })(name, prop[name]);
  150. Object.defineProperty(prototype, name, desc);
  151. } else if (isFunc) {
  152. desc.value = prop[name];
  153. Object.defineProperty(prototype, name, desc);
  154. } else {
  155. prototype[name] = prop[name];
  156. }
  157. if (isFunc) {
  158. // Override registered getter/setter
  159. var getter, setter, propertyName;
  160. if (this.__getters__ && this.__getters__[name]) {
  161. propertyName = this.__getters__[name];
  162. for (var i in this.__setters__) {
  163. if (this.__setters__[i] == propertyName) {
  164. setter = i;
  165. break;
  166. }
  167. }
  168. cc.defineGetterSetter(prototype, propertyName, prop[name], prop[setter] ? prop[setter] : prototype[setter], name, setter);
  169. }
  170. if (this.__setters__ && this.__setters__[name]) {
  171. propertyName = this.__setters__[name];
  172. for (var i in this.__getters__) {
  173. if (this.__getters__[i] == propertyName) {
  174. getter = i;
  175. break;
  176. }
  177. }
  178. cc.defineGetterSetter(prototype, propertyName, prop[getter] ? prop[getter] : prototype[getter], prop[name], getter, name);
  179. }
  180. }
  181. }
  182. }
  183. // And make this Class extendable
  184. Class.extend = cc.Class.extend;
  185. //add implementation method
  186. Class.implement = function (prop) {
  187. for (var name in prop) {
  188. prototype[name] = prop[name];
  189. }
  190. };
  191. return Class;
  192. };
  193. })();
  194. /**
  195. * Common getter setter configuration function
  196. * @function
  197. * @param {Object} proto A class prototype or an object to config<br/>
  198. * @param {String} prop Property name
  199. * @param {function} getter Getter function for the property
  200. * @param {function} setter Setter function for the property
  201. * @param {String} getterName Name of getter function for the property
  202. * @param {String} setterName Name of setter function for the property
  203. */
  204. cc.defineGetterSetter = function (proto, prop, getter, setter, getterName, setterName){
  205. if (proto.__defineGetter__) {
  206. getter && proto.__defineGetter__(prop, getter);
  207. setter && proto.__defineSetter__(prop, setter);
  208. } else if (Object.defineProperty) {
  209. var desc = { enumerable: false, configurable: true };
  210. getter && (desc.get = getter);
  211. setter && (desc.set = setter);
  212. Object.defineProperty(proto, prop, desc);
  213. } else {
  214. throw new Error("browser does not support getters");
  215. }
  216. if(!getterName && !setterName) {
  217. // Lookup getter/setter function
  218. var hasGetter = (getter != null), hasSetter = (setter != undefined), props = Object.getOwnPropertyNames(proto);
  219. for (var i = 0; i < props.length; i++) {
  220. var name = props[i];
  221. if( (proto.__lookupGetter__ ? proto.__lookupGetter__(name)
  222. : Object.getOwnPropertyDescriptor(proto, name))
  223. || typeof proto[name] !== "function" )
  224. continue;
  225. var func = proto[name];
  226. if (hasGetter && func === getter) {
  227. getterName = name;
  228. if(!hasSetter || setterName) break;
  229. }
  230. if (hasSetter && func === setter) {
  231. setterName = name;
  232. if(!hasGetter || getterName) break;
  233. }
  234. }
  235. }
  236. // Found getter/setter
  237. var ctor = proto.constructor;
  238. if (getterName) {
  239. if (!ctor.__getters__) {
  240. ctor.__getters__ = {};
  241. }
  242. ctor.__getters__[getterName] = prop;
  243. }
  244. if (setterName) {
  245. if (!ctor.__setters__) {
  246. ctor.__setters__ = {};
  247. }
  248. ctor.__setters__[setterName] = prop;
  249. }
  250. };
  251. /**
  252. * Create a new object and copy all properties in an exist object to the new object
  253. * @function
  254. * @param {object|Array} obj The source object
  255. * @return {Array|object} The created object
  256. */
  257. cc.clone = function (obj) {
  258. // Cloning is better if the new object is having the same prototype chain
  259. // as the copied obj (or otherwise, the cloned object is certainly going to
  260. // have a different hidden class). Play with C1/C2 of the
  261. // PerformanceVirtualMachineTests suite to see how this makes an impact
  262. // under extreme conditions.
  263. //
  264. // Object.create(Object.getPrototypeOf(obj)) doesn't work well because the
  265. // prototype lacks a link to the constructor (Carakan, V8) so the new
  266. // object wouldn't have the hidden class that's associated with the
  267. // constructor (also, for whatever reasons, utilizing
  268. // Object.create(Object.getPrototypeOf(obj)) + Object.defineProperty is even
  269. // slower than the original in V8). Therefore, we call the constructor, but
  270. // there is a big caveat - it is possible that the this.init() in the
  271. // constructor would throw with no argument. It is also possible that a
  272. // derived class forgets to set "constructor" on the prototype. We ignore
  273. // these possibities for and the ultimate solution is a standardized
  274. // Object.clone(<object>).
  275. var newObj = (obj.constructor) ? new obj.constructor : {};
  276. // Assuming that the constuctor above initialized all properies on obj, the
  277. // following keyed assignments won't turn newObj into dictionary mode
  278. // becasue they're not *appending new properties* but *assigning existing
  279. // ones* (note that appending indexed properties is another story). See
  280. // CCClass.js for a link to the devils when the assumption fails.
  281. for (var key in obj) {
  282. var copy = obj[key];
  283. // Beware that typeof null == "object" !
  284. if (((typeof copy) == "object") && copy &&
  285. !(copy instanceof cc.Node) && !(copy instanceof HTMLElement)) {
  286. newObj[key] = cc.clone(copy);
  287. } else {
  288. newObj[key] = copy;
  289. }
  290. }
  291. return newObj;
  292. };