获取"这个“;在父类中

Get "this" within the parent class

本文关键字:父类 这个 quot 获取      更新时间:2023-09-26

我的问题是我无法访问父类中正确的this对象。

父类:

ViewController.prototype.display = function() {
    console.log(this); // Log a Window object
};

子类:

ParentMissionsViewController.prototype = Object.create(ViewController.prototype);
ParentMissionsViewController.prototype.constructor = ParentMissionsViewController;
ParentMissionsViewController.prototype.parent = ViewController.prototype;
ParentMissionsViewController.prototype.display = function() {
    // Other stuff here
    this.parent.display.call();
};

我不明白为什么这不是我现在的对象,如果有人能解释我的话?

如果您调用

this.parent.display();

然后它看起来像:

var that = this.parent;
that.display();

我想你是想避免的。使用call是一种好方法,但您需要提供this:的值

this.parent.display.call(this /* , arg, arg... */);

参见MDN上call的签名。

尝试

this.parent.display();

当您使用调用来调用一个方法时,需要将自定义的this值指定为第一个参数。您在当前代码中得到的值是多少?我猜是未定义?