[英]JavaScript inheritance and super constructor
我已經從coffeescript找到並改編了JavaScript“類”擴展功能:
var extend = (function() {
var hasProp = Object.prototype.hasOwnProperty;
function ctor(child) {
this.constructor = child;
}
return function(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) {
child[key] = parent[key];
}
}
ctor.prototype = parent.prototype;
child.prototype = new ctor(child);
child.__super__ = parent.prototype;
// child.prototype.__super__ = parent.prototype; // better?
return child;
};
})();
我想知道他們是否有理由使用child.__super__
而不是child.prototype.__super__
(請參見注釋掉的代碼行)。
我更喜歡注釋過的版本,因為:
您可以通過this.__super__.propertyName
而不是ClassName.__super__.propertyName
來訪問超級ClassName.__super__.propertyName
。 因此,在類命名中沒有多余的內容。
對於嵌套繼承,這更有意義,因為可以使用this.__super__.__super__.propertyName
代替ClassName.__super__.constructor.__super__.propertyName
我看不出有什么原因,但是您仍然可以像這樣的“靜態”方式調用“靜態”函數:
ClassName.prototype.__super__.constructor.staticMethod()
我的版本是否有任何我可能會忽略的缺點?
編輯:我將行更正為var hasProp = Object.prototype.hasOwnProperty;
因為您根本不應該在代碼中使用__super__
。
這是一個編譯器工件,每次對super
宏/關鍵字/進行任何使用都會編譯為
ClassName.__super__.methodName.call(this, …) // or
ClassName.__super__.methodName.apply(this, …)
// or, in static class functions even
ClassName.__super___.constructor.functionName.call(this, …)
他們不信任您建議使用的動態this
綁定 ( this.__super__
),而是去尋求父級的靜態引用。 實際上,最好根本不使用屬性,而只在模塊范圍內使用局部super
變量。
另外, this.__super__
不能在繼承的方法中工作:
function A() { }
A.prototype.method = function() { console.log("works") };
function B() { A.call(this); }
B.prototype = Object.create(A.prototype);
B.prototype.__super__ = A.prototype;
B.prototype.method = function() { this.__super__.method.call(this); }
function C() { B.call(this); }
C.prototype = Object.create(B.prototype);
C.prototype.__super__ = B.prototype;
var b = new B(), c = new C();
b.method() // "works"
c.method() // Maximum recursion depth exceeded
堆棧溢出,因為您沒有獲得預期的.__super__
!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.