博客网址 -> http://ejohn.org/blog/simple-javascript-inheritance/。
这是片段。
var _super = this.prototype;
initializing = true;
var prototype = new this();
initializing = false;
我对 new this(); 的使用感到困惑。
博客网址 -> http://ejohn.org/blog/simple-javascript-inheritance/。
这是片段。
var _super = this.prototype;
initializing = true;
var prototype = new this();
initializing = false;
我对 new 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是 (ie, function-property of) 的一种方法Class。在任何方法里面,this指的是对象它们是[1]的方法。所以里面Class.extend,this === Class。因此new this()等价于new Class()。
他这样做的原因有点奇怪。他试图建立某种“类层次结构”,其中一切都源自 . Class,有点像 Java 或 C# 中的一切都源自Object.
我不会推荐这种方法。
[1] 仅当方法作为方法调用时才成立,例如Class.extend(...),而不是当它作为函数调用时,例如var extend = Class.extend; extend(...)。
继承:(取自这里)
ChildClassName.prototype = new ParentClass();.ChildClassName.prototype.constructor = ChildClassName.这里new this()所指的 ParentClass 被继承 & 存储在变量prototype中。
您提到的代码中原型变量发生的情况也类似。
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;