我不认为使“这个”不受约束是一个错误。起初有时可能会令人困惑,但它的方式有充分的理由。首先想到的是,由于 JavaScript 不是基于类的语言,函数不与任何特定的类相关联,因此没有一致的方式将“this”自动绑定到正确的对象实例。例如,
function Person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
Person.prototype.getFullName = function() {
return this.firstName + " " + this.lastName;
};
"this" 需要引用一个 Person 对象,但是分配给 Person.prototype.getName 的函数没有任何方法知道它将如何使用,因此 "this" 需要绑定到它所调用的任何对象在。
当你有嵌套函数时,这会导致问题。
// This is a really contrived example, but I can't think of anything better
Person.prototype.getInfo = function() {
// get name as "Last, First"
function getNameLastFirst() {
// oops. "this" is the global object, *not* the Person
return this.lastName + ", " + this.firstName;
}
// expect something like "Crumley, Matthew: Age 25",
// but you get "undefined, undefined: Age 25"
return getNameLastFirst() + ": Age " + this.age;
};
建议的语法人工白痴会很方便,但使用 apply 将“this”绑定到特定对象非常容易:
function bind(func, obj) {
return function() {
return func.apply(obj, arguments);
};
}
Person.prototype.getInfo = function() {
// get name as "Last, First"
var getNameLastFirst = bind(function () {
return this.lastName + ", " + this.firstName;
}, this);
return getNameLastFirst() + ": Age " + this.age;
};
或更“传统”的使用闭包的方法:
Person.prototype.getInfo = function() {
var self = this;
// get name as "Last, First"
function getNameLastFirst() {
return self.lastName + ", " + self.firstName;
}
return getNameLastFirst() + ": Age " + this.age;
};