Javascript 重写继承的原型方法并在新方法中调用原始方法
在下面的代码段中,如何访问Javascript 重写继承的原型方法并在新方法中调用原始方法,javascript,inheritance,overriding,prototype,Javascript,Inheritance,Overriding,Prototype,在下面的代码段中,如何访问B.prototype.log中的A.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 () { //ca
B.prototype.log
中的A.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)
,但我想也许有一种更优雅的方式,让我以相对的方式调用它,比如“调用prototype链中下一个更高实例的方法'log'。这样做可能吗?您可以使用
注意:Object.getPrototypeOf是ECMAScript 5,请参见
还有非标准的和不推荐使用的属性() 引用与其内部[[Prototype]]相同的对象 并允许您像这样调用
A
s'log方法
B.prototype.\uuuuu proto\uuuuu.log.call(this)
但是
首选方法是使用Object.getPrototypeOf
实际上,
A.prototype.log.call(这个)
正是我搜索的内容。谢谢大家!@C5H8NNaO4代码中有一个类型,正确的类型是Object.getPrototypeOf(B.prototype.log)。调用(this)
...
B.prototype.log = function () {
Object.getPrototypeOf (B.prototype).log.call(this)
console.log("B");
};
...
b.log(); //A B