我有以下代码:
var first = function() {
this.loc = '1';
this.test = function() {
console.log('first ' + this.loc);
}
}
var second = function() {
var me = this;
this.loc = '2';
this.test = function() {
console.log('second ' + this.loc);
Object.getPrototypeOf(me).test.call(me);
}
}
second.prototype = new first();
var third = function() {
var me = this;
this.loc = '3';
this.test = function() {
console.log('third ' + this.loc);
Object.getPrototypeOf(me).test.call(me);
}
}
third.prototype = new second();
var t = new third();
t.test();
它将输出:
third 3
second 3
first 2
我如何使其输出:
third 3
second 3
first 3
所以我想用最后一个继承的类覆盖第一类的loc值。
最佳答案
将thisArg
对象函数调用的fun.call(thisArg[, arg1[, arg2[, ...]]])
(签名second
)从me
更改为this
:
...
var second = function() {
var me = this;
this.loc = '2';
this.test = function() {
console.log('second ' + this.loc);
Object.getPrototypeOf(me).test.call(this); // <--
}
}
...
进行方式:
第一次,在
test()
实例输出third
时调用"third 3"
函数然后,由
test
在相同的second
实例上从third
实例(作为third
原型)调用Object.getPrototypeOf(me).test.call(me);
函数当
test
函数正在执行时this
关键字应指向third
实例并传递给进一步的test()
调用