我有以下代码:



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()调用

10-05 20:40
查看更多