[英]Javascript inheritance with access to *all* methods in 'superclass'?
為了理解如何在Java語言中完成繼承,我偶然發現了許多不同的實現,包括Crockfords,Resigs, Prototype
, klass
等。
我想念的(我為這場騷動感到鼓舞)是Smalltalkish的self / super對: self
扮演的角色與this
類似,即代表當前的“對象”,並且super
引用了this
的僅超類版本。
[跳轉到“]”如果你知道super
確實在Smalltalk:假設Subclass
已重寫method1
中定義的Superclass
,我仍然可以訪問超類實現使用super.method1()
在Subclass.method2()
這將不會執行Subclass.method1()
代碼。
function Superclass () {
}
Superclass.prototype.method1 = function () {
return "super";
}
function Subclass () {
}
Subclass.prototype.method1 = function () {
return "sub";
}
Subclass.prototype.method2 = function () {
alert (super.method1 ());
}
var o = new Subclass;
o.method2 (); // prints "super"
]
有沒有“ Javatalk”軟件包? 到目前為止,我只看到Java腳本中的OO仿真,該仿真可以訪問當前定義的方法( method2
)的超類實現,而不能訪問任何其他類(例如method1
)。
謝謝,諾比
您在JavaScript中沒有super
功能。
Superclass.method1.call(this);
如果要模擬通用super
(我不主張),則可以使用以下方法:
function sup(obj, name) {
var superclass = Object.getPrototypeOf(Object.getPrototypeOf(obj));
return superclass[name].apply(obj, [].slice.call(arguments,2));
}
您將用作
sup(this, 'method1');
而不是你的
super.method1();
如果您有要傳遞的參數:
sup(this, 'method1', 'some', 'args');
代替
super.method1('some', 'args');
請注意,這假設您使用設置了正確的原型繼承
Subclass.prototype = new Superclass();
Okey,長話短說: 這是我讀過的最好的JavaScript教程。 所以我可以推薦給您。 祝好運!
在JavaScript中實現super
功能的方法有很多。 例如:
function SuperClass(someValue) {
this.someValue = someValue;
}
SuperClass.prototype.method1 = function () {
return this.someValue;
};
function SubClass(someValue) {
//call the SuperClass constructor
this.super.constructor.call(this, someValue);
}
//inherit from SuperClass
SubClass.prototype = Object.create(SuperClass.prototype);
//create the super member that points to the SuperClass prototype
SubClass.prototype.super = SuperClass.prototype;
SubClass.prototype.method2 = function () {
alert(this.super.method1.call(this));
};
var sub = new SubClass('some value');
sub.method2();
編輯:
這是一個依靠非標准功能的極其通用的super
方法的示例。 我真的不建議這樣做,它只是作為學習目的。
Object.prototype.super = function () {
var superProto = Object.getPrototypeOf(Object.getPrototypeOf(this)),
fnName = arguments.callee.caller.name,
constructorName = this.constructor.name;
if (superProto == null) throw constructorName + " doesn't have a superclass";
if (typeof superProto[fnName] !== 'function') {
throw constructorName + "'s superclass ("
+ superProto.constructor.name + ") doesn't have a " + fnName + ' function';
}
return superProto[arguments.callee.caller.name].apply(
this,
[].slice.call(arguments, 1)
);
};
function A() {
}
A.prototype.toString = function toString() {
//call super method Object.prototype.toString
return this.super();
};
var a = new A();
console.log(a.toString());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.