博客网址->http://ejohn.org/blog/simple-javascript-inheritance/。
这是片段。
var _super = this.prototype;
initializing = true;
var prototype = new this();
initializing = false;
我被新this()的使用难住了;
在上下文中查看它会有所帮助。即:
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;
注意,extend
是Class
的一种方法(即,的函数性质)。在任何方法中,this
指的是它们是[1]方法的对象。所以在Class.extend
,this === Class
里面。因此CCD_ 6等同于CCD_。
他这么做的原因有点奇怪。他试图建立某种"类层次结构",所有东西都从Class
派生,有点像Java或C#中的所有东西都是从Object
派生的。
我不推荐这种方法。
[1] 只有当方法被调用为方法(例如Class.extend(...)
)时,这才是真的,而不是当它被调用为函数时,例如var extend = Class.extend; extend(...)
。
对于继承:(取自此处)
- 您使用
ChildClassName.prototype = new ParentClass();
使类继承 - 您需要记住重置类的构造函数属性使用CCD_ 13
这里CCD_ 14指的是被继承的ParentClass&存储在变量原型中。
您引用的代码中的原型变量也发生了类似的情况。
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;