6

次のコードでは、どのようにA.prototype.log内部にアクセスできますB.prototype.logか?

function A() {}

A.prototype.log = function () {
    console.log("A");
};

function B() {}

B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

B.prototype.log = function () {
    //call A.prototype.log here
    console.log("B");
};

var b = new B();
b.log();

私はただ書くことA.prototype.log.call(this)ができることを知っていますが、「プロトタイプチェーンの次の上位インスタンスのメソッド 'log' を呼び出す」のように、相対的な方法で呼び出すことができる、よりエレガントな方法があるのではないかと思いました。このようなことは可能ですか?

4

1 に答える 1

5

You could use Object.getPrototypeOf

...
B.prototype.log = function () {
    Object.getPrototypeOf (B.prototype).log.call(this)
    console.log("B");
};
...
b.log(); //A B

Note: Object.getPrototypeOf is ECMASript 5, see the compatibility


There is also the non standard and deprecated __proto__ property (compatibility) which

references the same object as its internal [[Prototype]]

and would allow you to call your As' log method like this

B.prototype.__proto__.log.call(this)

But

the preferred method is to use Object.getPrototypeOf.

于 2013-07-25T13:00:12.813 に答える