this
(又名“上下文”)是每个功能内的特殊关键字和它的值仅取决于 如何 调用函数,而不是如何/何时/何它被定义。它不受其他变量之类的词法作用域的影响(箭头函数除外,请参见下文)。这里有些例子:
function foo() {
console.log(this);
}
// normal function call
foo(); // `this` will refer to `window`
// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`
// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`
要了解更多信息this
,请查看MDN文档。