我对 JavaScript 还是很陌生,我刚刚开始使用.apply()
和其他使用关键字的方法this
,我可以看出这this
与调用函数的上下文有关,但我真的很想了解究竟this
指的是什么。
特定函数调用之间的this
关系看起来类似于对象和属性/方法之间的关系。
这两种关系到底有没有关系?
我对 JavaScript 还是很陌生,我刚刚开始使用.apply()
和其他使用关键字的方法this
,我可以看出这this
与调用函数的上下文有关,但我真的很想了解究竟this
指的是什么。
特定函数调用之间的this
关系看起来类似于对象和属性/方法之间的关系。
这两种关系到底有没有关系?
According to the ECMAScript Language Specification Section 11.1.1 the answer is
The this keyword evaluates to the value of the ThisBinding of the current execution context.
以下是三种情况,您可以考虑。没有正式描述,而是简单直观:
默认上下文
如果您不指定上下文并调用函数(而不是方法),this
则将是全局对象:
function foo() {
console.log(this); //window
}
隐式设置上下文
如果你调用一个函数,给定对象的方法this
将是最后一个点之前的对象:
function foo() {
console.log(this);
}
var bar = {};
bar.foo = foo;
bar.foo(); //bar
bar.baz = {};
bar.baz.foobar = foo;
bar.baz.foobar(); //bar.baz
显式设置上下文
call
您可以使用, apply
,更改上下文bind
:
function foo() {
console.log(this);
}
foo.call(1); //1
foo.call(window); //window
var bar = {};
bar.foo = foo;
bar.foo.apply(42); //42