繁体   English   中英

“this”如何在构造函数中分配的函数中工作?

[英]How does “this” work in functions that are assigned in the constructor?

我找到了这个示例代码:

function personFullName() {
    return this.first + ' ' + this.last;
}

function Person(first, last) {
    this.first = first;
    this.last = last;
    this.fullName = personFullName;
}

var dude = new Person("Michael", "Jackson");
alert(dude.fullName());

哪个警告“迈克尔杰克逊”。 我将其更改为从构造函数调用personFullName而不是分配函数对象:

function personFullName() {
    return this.first + ' ' + this.last;
}

function Person(first, last) {
    this.first = first;
    this.last = last;
    this.fullName = personFullName();
}

var dude = new Person("Michael", "Jackson");
alert(dude.fullName);

我希望“fullName”属性现在是一个字符串而不是一个函数。 但现在它警告“undefined undefined”。 任何人都可以解释为什么我的版本不起作用?

在JavaScript中, this通常是在之前的任何事情. 在函数调用中。 所以你说dude.fullName()的原因是this fullName()中的这个设置为dude 1

在您的问题的第二个版本中,您没有以相同的方式调用它。 你在调用personFullName()没有任何东西(这是正确的,因为它不再附加到Person对象)。 这意味着this最终默认为与window相同的值。 由于window上没有设置firstlast属性,因此this.firstthis.lastundefined

要解决此问题,您可以将您的人员作为personFullName()函数的参数:

function personFullName(person) {
    return person.first + ' ' + person.last;
}

然后把它称为

…
this.fullName = personFullName(this);

1:请注意,该方法必须是对象的属性才能使this绑定起作用。 你不能只调用object.someMethod()并在someMethod this set设置为object 在您的代码中,以下内容不起作用:

function Person(first, last) {
    this.first = first;
    this.last = last;
    this.fullName = this.personFullName();
}

Uncaught TypeError: this.personFullName is not a function

这也不是:

function personFullName() {
    return this.first + ' ' + this.last;
}

function Person(first, last) {
    this.first = first;
    this.last = last;
}

var dude = new Person("Michael", "Jackson");
alert(dude.personFullName());

Uncaught TypeError: dude.personFullName is not a function

你可以在任何情况下使用apply helper方法解决这个限制: this.fullName = personFullName.apply(this)执行你希望你的代码的第二个版本做什么,你也可以在任何地方调用personFullName.apply(dude)指出并让"Michael Jackson"回归。

this是你的personFullName函数中的窗口,因为它没有在正确的上下文中调用。 您可以使用apply使用正确的上下文调用它,而无需修改personFullName函数。

function personFullName() {
    return this.first + ' ' + this.last;
}

function Person(first, last) {
    this.first = first;
    this.last = last;
    this.fullName = personFullName.apply(this); // The magic
}

var dude = new Person("Michael", "Jackson");
alert(dude.fullName);

修复的更好的替代方案是:

Person.prototype.personFullName = function() {
    return this.first + ' ' + this.last;
}

中,你正在访问的上下文this在第二个例子中,是引用window对象。 window没有设置fullName属性。 如果你添加alert(this); 对于这两个功能,你会看到我的意思。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM