Javascript继承,可以访问“超类”中的*所有*方法

Javascript inheritance with access to *all* methods in 'superclass'?

本文关键字:中的 所有 方法 超类 继承 访问 Javascript      更新时间:2023-09-26

为了理解如何在Javascript中完成继承,我偶然发现了许多不同的实现,包括Crockfords,Resigs,Prototypeklass等。

错过的(我为轩然做好准备)是Smalltalkish自我/超级对:self扮演着与this类似的角色,即代表当前的"对象",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)。

谢谢,诺比

JavaScript 中没有super功能。

当你知道超类时,你可以使用 call 直接调用超方法:

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();

有很多方法可以在 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());

Okey,长话短说:这是我读过的最好的JavaScript教程。所以我可以向你重新评论。祝你好运!