1

我正在使用js.class,我希望能够在子类中调用超类的函数。我知道我可以用来this.callSuper()从超类调用当前被覆盖的函数,但是调用其他被覆盖的函数呢?

例如在Java中我可以这样做:

class SuperClass {
    void myMethod() {
        // Do something!
    }
}

class SubClass extends SuperClass {
    void myMethod() {
        // Do something else!
    }
    void anotherMethod() {
        super.myMethod(); // call the original myMethod form the SuperClass
    }
}

在 js.class 中有可能吗?!

4

2 回答 2

1

是的,只要对 JavaScript 中的“类”如何工作有一点了解,这是可能的。

JavaScript 类基础

(如果你已经知道这一点,你可以跳过这部分)

JavaScript 中的“类”实际上只是一个具有名为prototype. 此prototype属性提供默认实例方法和属性。

让我们以两个示例类PointPoint3D.

function Point(x, y) {
    this.x = x;
    this.y = y;
}

Point.prototype = {
    x: 0,
    y: 0,

    constructor: Point,

    isAbove: function(point) {
        return this.y > point.y;
    },

    isBelow: function(point) {
        return this.y < point.y;
    }
};

该类Point是我们的基类,表示 x 和 ay 坐标。该类Point3D继承自Point并具有 az 坐标(忽略任何数学错误)。

function Point3D(x, y, z) {
    Point.call(this, x, y);
    this.z = z;
}

Point3D.prototype = new Point(0, 0);

Point3D.prototype.constructor = Point3D;

Point3D.prototype.isAbove = function(point) {
    return Point.prototype.isAbove.call(this, point);
};

Point3d.prototype.isDiagonal = function(point) {
    return Point.prototype.isAbove.call(this, point)
        && this.x > point.x;
};

isDiagonal方法中,我们调用isAbovePoint 类的方法,尽管 Point3D 实现了自己的版本。

调用重写的方法

您可以使用此基本模板在任何类上调用任何覆盖的方法:

ClassName.prototype.method.call(this, arg1, arg2, ... argN);
于 2013-12-26T14:05:24.763 回答
1

js.class如果你知道什么A是超级的,你就可以做到B

A = function (x) { this.x = x};
A.prototype.myMethod = function () {return this.x + 1};
B = function (x) { A.call(this,x)};
B.prototype = new A();
B.prototype.myMethod = function () {return this.x + 2};
B.prototype.anotherMethod = function () {return A.prototype.myMethod.call(this)};

如果你不知道谁是 B 的父母,你可以__proto__在它支持的地方使用:

B.prototype.anotherMethod = function () {this.__proto__.myMethod.call(this)};

如果你真的需要js.class试试这个(现在检查这个):

var A = new Class({
    extend: {
        inherited: function(childClass) {
            childClass.super = this.klass;
        }
    },
    initialize: function(x) {
        this.x = x;
    },

    myMethod: function() {
        return this.x + 1;
    }
});

var B = new Class(A, {
    initialize: function(x) {
        this.callSuper(x);
    },

    myMethod: function() {
        return this.x + 2;
    },
    anotherMethod: function () {
        return this.super.myMethod()
    }
});
于 2013-12-26T13:40:25.687 回答