/* Simple JavaScript Inheritance * By John Resig http://ejohn.org/ * MIT Licensed. */ // Inspired by base2 and Prototype (function(){ var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; // The base Class implementation (does nothing) this.Class = function(){}; // Create a new Class that inherits from this class Class.extend = function(prop) { var _super = this.prototype; // Instantiate a base class (but only create the instance, // don't run the init constructor) initializing = true; var prototype = new this(); initializing = false; // Copy the properties over onto the new prototype for (var name in prop) { // Check if we're overwriting an existing function prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function(name, fn){ return function() { var tmp = this._super; // Add a new ._super() method that is the same method // but on the super-class this._super = _super[name]; // The method only need to be bound temporarily, so we // remove it when we're done executing var ret = fn.apply(this, arguments); this._super = tmp; return ret; }; })(name, prop[name]) : prop[name]; } // The dummy class constructor function Class() { // All construction is actually done in the init method if ( !initializing && this.init ) this.init.apply(this, arguments); } // Populate our constructed prototype object Class.prototype = prototype; // Enforce the constructor to be what we expect Class.prototype.constructor = Class; // And make this class extendable Class.extend = arguments.callee; return Class; }; })();
與Java中的Object一樣所有類都直接或間接繼承于Class,下面是繼承Class實例:
var Person = Class.extend({ ① init: function (isDancing) { ② this.dancing = isDancing; }, dance: function () { ③ return this.dancing; } }); var Ninja = Person.extend({ ④ init: function () { ⑤ this._super(false); ⑥ }, dance: function () { ⑦ // Call the inherited version of dance() return this._super(); ⑧ }, swingSword: function () { ⑨ return true; } }); var p = new Person(true); ⑩ console.log(p.dance());// true var n = new Ninja(); console.log(n.dance()); // false console.log(n.swingSword()); // true
如果你對于Java語言的面向對象很熟悉的話,應該很容易看懂。其中第①行代碼是聲明Person類,它繼承自Class,Class.extend()表示繼承自Class。第②行代碼的定義構造函數init,它的作用是初始化屬性。第③行代碼是定義普通函數dance(),它可以返回屬性dancing。
第④行代碼是聲明Ninja類繼承自Person類,第⑤行代碼的定義構造函數init,在該函數中this._super(false)語句是調用父類構造函數初始化父類中的屬性,見代碼第⑥行所示。第⑦行代碼是重寫dance()函數,它會覆蓋父類的dance()函數。第⑧行代碼是this._super()是調用父類的dance()函數。第⑨行代碼是子類Ninja新添加的函數swingSword()。
第⑩行代碼通過Person類創建p對象,給構造函數的參數是true。第行代碼是打印日志p對象dance屬性,結果為true。
第行代碼通過Ninja類創建n對象,構造函數的參數為空,默認初始化采用false初始化父類中的dance屬性。因此在代碼第行打印為false。
這種簡單JavaScript繼承方法事實上實現了一般意義上的面向對象概念的繼承和多態機制。這種簡單JavaScript繼承方法是Cocos2d-JS繼承機制的核心,Cocos2d-JS稍微做了修改,熟悉簡單JavaScript繼承的用法對于理解和學習Cocos2d-JS非常的重要。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com