为了理解如何在Javascript中实现继承,我偶然发现了许多不同的实现,包括Crockfords、Resigs、Prototype
、klass
和其他实现。
我错过的(我准备好面对喧嚣)是Smalltalkish self/Super结对:self
扮演着与this
相似的角色,即表示当前的"object",super
指的是只使用超类的this
版本。
如果您知道super
在Smalltalk中做了什么:假设Subclass
已经覆盖了在Superclass
中定义的method1
,那么我仍然可以使用Subclass.method2()
中的super.method1()
访问超类实现。这将不会执行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“包吗?到目前为止,我只看到Javascript中的OO仿真,它允许访问当前定义的方法(method2
)的超类实现,而不是任何其他的(比如method1
)。
谢谢你,诺比
发布于 2013-09-12 14:10:32
在super
中实现JavaScript特性的方法太多了。例如:
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());
发布于 2013-09-12 14:04:49
在super
中没有JavaScript特性。
当您知道超类时,可以直接使用打电话调用超级方法:
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();
发布于 2013-09-12 13:56:10
好吧,长话短说:这是我读过的最好的JavaScript教程。所以我可以重新评论给你听。祝好运!
https://stackoverflow.com/questions/18766212
复制相似问题