JavaScript 中 this 是如何工作的?

this 永远指向函数运行时所在的对象,而不是函数被创建时所在的对象。
匿名函数或不处于任何对象中的函数指向 window 。例:

1
var foo = { bar : function(){ console.log(this === foo); } }
foo.bar() 输出 true

2
var foo = { bar : function(){ (function(){ console.log(this); })(); } }
foo.bar() 输出 DOMWindow

3
var foo = { bar : { baz : function(qux){ console.log(this === qux); } } }
foobar = foo.bar;
foobar.baz(foo.bar) 输出 true

但是⋯⋯

wtf = foo.bar.baz;
wtf(foo.bar) 输出 false

为什么?因为 wtf 不是在一个对象中被调用的,this 指向 DOMWindow 。验证:
console.log(this) 输出 DOMWindow
wtf(this) 输出 true

没明白你说的控制 this 指向是什么意思,this 所指的东西是语言机制的一部分,你控制不了。如果你是问怎么在函数里保留一份其运行时所在对象的 reference,可以用闭包(closure):

var foo = {
whoami : "duh i am foo",
bar : function(){
var shit = this;
return function(){
console.log(shit.whoami);
console.log(this);
};
}
};

baz = foo.bar();

此时 baz 是一个脱离 foo.bar 而存在的函数,但是:

baz() 会输出 duh i am foo 和 DOMWindow 。
原发布于 https://www.zhihu.com/question/19624483/answer/12426658