在 JavaScript 中使用构造函数调用时,我读到函数中的 this 变量/关键字将绑定到新对象,并将返回一个具有所有绑定“this”值的对象。
例如:
function Person() {
this.name = "bob";
this.age = 33;
}
var person = new Person(); // person object with name property of "bob" and age property of 33
如果我做这样的事情,同样的结果会发生:
function Person() {
var localVar = "test",
fake = "fake";
this.name = "bob";
this.age = 33;
}
var person = new Person(); // person object with name property of "bob" and age property of 33 regardless of the local variables declared inside
但是,如果我这样做,在 self 上声明的变量/属性将在对象中返回
function Person() {
var self = this;
self.phone = "123-123-1222";
self.career = "programmer";
this.name = "bob";
this.age = 33;
}
var person = new Person(); // person object with name property of "bob" and age property of 33, phone of "123-123-1222" and career of "programmer"
在最后一个示例中,解释器如何知道返回所有四个属性,即使其中两个绑定到 this 的局部变量而不是实际的“this”关键字。