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

ran*_*uff 5 javascript constructor function this

我找到了这个示例代码:

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());
Run Code Online (Sandbox Code Playgroud)

哪个警告"迈克尔杰克逊".我将其更改为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);
Run Code Online (Sandbox Code Playgroud)

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

Str*_*ior 6

在JavaScript中,this通常是.函数调用之前的任何内容.所以你说的其实dude.fullName()是什么原因造成thisfullName()设置为dude1.

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

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

function personFullName(person) {
    return person.first + ' ' + person.last;
}
Run Code Online (Sandbox Code Playgroud)

然后把它称为

…
this.fullName = personFullName(this);
Run Code Online (Sandbox Code Playgroud)

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

function Person(first, last) {
    this.first = first;
    this.last = last;
    this.fullName = this.personFullName();
}
Run Code Online (Sandbox Code Playgroud)

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());
Run Code Online (Sandbox Code Playgroud)

Uncaught TypeError: dude.personFullName is not a function

您可以使用apply帮助程序方法在任何情况下解决此限制:this.fullName = personFullName.apply(this)执行您希望代码的第二个版本执行的操作,并且您也可以随时调用personFullName.apply(dude)"Michael Jackson"返回.