本文转载于网络,侵权必删

在 JavaScript 中,this 是一个相对难懂的特殊变量。因为它随处可用,而不仅仅是面向对象的编程中。本文将解释 this 是如何工作的,以及它可能导致问题的地方,并在文章的给出最佳实践。
为了方便理解 this ,最好的方式是根据使用 this 的位置划分三种类型:
- 在函数内部: this 是一个额外的隐含的参数。
- 在函数外部(顶级作用域中): this 在浏览器中指向全局对象;在 Node.jS 中指向 模块(module) 的接口(exports)。
- 在传递给 eval() 的字符串中: eval() 如果是被直接调用, this 指的是当前对象;如果是被间接调用,this 指的是全局对象。
我们来看看每个类别。
1.函数内部的 this

这是 this 最常用的使用场景,因为 JavaScript 中,以三种不同的角色代表了所有的可调用的结构形式:
- 真正函数( this 在松散模式下是全局对象,严格模式下是 undefined )
- 构造函数( this 指向刚创建的实例 )
- 方法: (this 指向方法调用的接受对象 )
在函数中,this 可以理解为一个额外隐含的参数。
1.1 真正函数中的 this
在真正函数中,this 的值取决于函数所处的模式:
- 松散模式(Sloppy mode): this 指向全局对象 (浏览器中就是 window )。
JavaScript 代码:
function sloppyFunc() { console.log(this === window); // true}sloppyFunc();
- 严格模式:this 的值为 undefined 。
JavaScript 代码:
function strictFunc() { 'use strict'; console.log(this === undefined); // true}strictFunc();
也就是说,这是一个默认值( window 或 undefined )的隐式参数。但是,您可以通过 call() 或者 apply() 来调用函数,并明确的指定 this 的值。
JavaScript 代码:
function func(arg1, arg2) { console.log(this); // a console.log(arg1); // b console.log(arg2); // c}func.call('a', 'b', 'c'); // (this, arg1, arg2)func.apply('a', ['b', 'c']); // (this, arrayWithArgs)
1.2 构造函数中的 this
如果你通过 new 操作符来调用函数,则函数将成为构造函数。该操作符创建一个新的对象,并通过 this 把它传递给构造函数:
JavaScript 代码:
var savedThis;function Constr() { savedThis = this;}var inst = new Constr();console.log(savedThis === inst); // true
new 操作符在JavaScript中实现,大致如下(更精确的实现稍微复杂一点):
JavaScript 代码:
function newOperator(Constr, arrayWithArgs) { var thisValue = Object.create(Constr.prototype); Constr.apply(thisValue, arrayWithArgs); return thisValue;}
1.3 方法中的 this
在方法中,所有的事情都和传统的面向对象语言类似: this 指向接受对象,即方法被哪个对象调用。
JavaScript 代码:
var obj = { method: function () { console.log(this === obj); // true }}obj.method();
2.顶级作用域中的 this

在浏览器环境中,顶级作用域是全局作用域, this 指向 全局对象(诸如 window 之类):
HTML 代码:
在 Node.js 中,你通常在 模块(module) 中执行代码。因此,顶级作用域是一个指定模块的作用域(module scope)。
JavaScript 代码:
// `global` (not `window`) refers to global object:console.log(Math === global.Math); // true// this doesn’t refer to the global object: console.log(this !== global); // true // this refers to a module’s exports: console.log(this === module.exports); // true
3.eval() 中的 this
eval() 既可以被直接调用(通过一个真正函数调用),也可以被间接调用(通过另一些方式)。以下是具体解释。
如果 eavl() 被间接调用, this 指向 全局对象,在控制台中输入:
JavaScript 代码:
> (0,eval)('this === window')true
否者,如果 eval() 被直接调用,那么 this 指向 eval() 所处的执行环境。例如:
JavaScript 代码:
// Real functionsfunction sloppyFunc() { console.log(eval('this') === window); // true}sloppyFunc(); function strictFunc() { 'use strict'; console.log(eval('this') === undefined); // true}strictFunc(); // Constructorsvar savedThis;function Constr() { savedThis = eval('this');}var inst = new Constr();console.log(savedThis === inst); // true // Methodsvar obj = { method: function () { console.log(eval('this') === obj); // true }}obj.method();
4.this 相关的陷阱
这里有3个和 this 有关的陷阱值得注意的。 记住,严格模式可以使得每种情况变得正常,因为在真正函数中 this 都会为 undefined ,当出错的时候会收到警告。
4.1 忘记使用 new 操作符
如果你调用构造函数却忘记使用了 new 操作符,那么你会意外的调用一个真正函数。因此, this 不会指向正确的值。在松散模式中,this 指向 window ,并且会创建全局变量:
JavaScript 代码:
function Point(x, y) { this.x = x; this.y = y;}var p = Point(7, 5); // 我们忘记了 new!console.log(p === undefined); // true // 全局变量已创建:console.log(x); // 7console.log(y); // 5
幸好,在严格模式下你会收到一条警告( this === undefined):
JavaScript 代码:
function Point(x, y) { 'use strict'; this.x = x; this.y = y;}var p = Point(7, 5);// TypeError: Cannot set property 'x' of undefined
4.2 获取方法不当
如果你获取的是方法的值(而非调用),你会将方法又转变为函数。调用这个值的结果是一个函数调用,而不是一个方法调用。当你将方法作为函数或方法调用的参数传递时,可能会发生这种情况。真实的例子包括 setTimeout() 和 注册处理程序。我将使用 callIt() 函数同步模拟这个用例:
JavaScript 代码:
/* 与 setTimeout() 和 setImmediate() 类似 */function callIt( func ){ func();}
如果你调用一个松散模式下的函数, this 指向全局对象,并且创建全局变量:
JavaScript 代码:
var counter = { count: 0, // 松散模式下 method inc: function () { this.count++; }} callIt(counter.inc); // 不会:console.log(counter.count); // 0 // 相反,一个全局变量已经被创建// (NaN 是 undefined 应用 ++ 后结果):console.log(count); // NaN
如果你调用严格模式下的函数,this 为 undefined , 代码也将会无效。但是会收到一个警告。
JavaScript 代码:
var counter = { count: 0, // 严格模式下 method inc: function () { 'use strict'; this.count++; }} callIt(counter.inc); // TypeError: Cannot read property 'count' of undefinedconsole.log(counter.count);
可以使用 bind() 开解决:
JavaScript 代码:
var counter = { count: 0, inc: function () { this.count++; }} callIt(counter.inc.bind(counter)); // It worked!console.log(counter.count); // 1
bind() 创建一个接受的 this 值为 counter 的新函数。
4.3 覆盖 this
当你在一个方法中使用一个真正函数时,很容易忘记前者有它自己的 this 值(即使真正的函数中没用显式的使用 this )。 因此,你不能从真正函数中的 this引用到方法的 this,因为它是被覆盖的。 我们来看一个事情出错的例子:
JavaScript 代码:
var obj = { name: 'Jane', friends: [ 'Tarzan', 'Cheeta' ], loop: function () { 'use strict'; this.friends.forEach( function (friend) { console.log(this.name+' knows '+friend); } ); }};obj.loop();// TypeError: Cannot read property 'name' of undefined
在上面例子中,this.name 失败,原因是函数的 this 为 undefined ,他与 loop() 方法内的 this 并不是同一个 this ,这里有 3 种解决方案。
解决方案1: that = this。将 this 分配给一个变量,使其不再被覆盖(另一个常用的变量名为 self)再使用它。
JavaScript 代码:
loop: function () { 'use strict'; var that = this; this.friends.forEach(function (friend) { console.log(that.name+' knows '+friend); });}
解决方案2:bind()。使用 bind() 来创建一个 this 常指向当前值的函数(在下面这个例子中是:方法的 this)。
JavaScript 代码:
loop : function(){ 'use strict'; this.friends.forEach(function( friend ){ console.log( this.name + ' knows ' + friend ); }.bind( this ));}
解决方案3:forEach 的第二个参数。该方法有第二个参数,它的值作为this传递给回调函数。
JavaScript 代码:
loop : function(){ 'use strict'; this.friends.forEach(function( friend ){ console.log( this.name + ' knows ' + friend ); }, this );}
5.最佳实践
概念上来说,我认为真正函数并不具有它们自己的 this ,并且想到前面提到的解决方案就是保持这种错觉。ECMAScript 6 通过箭头函数来支持保持 this – 函数没有其自己的 this 值。在箭头函数中,你可以无忧无虑的使用 this ,因为不会被覆盖。
JavaScript 代码:
loop : function(){ 'use strict'; // forEach 的参数就是箭头函数 this.friends.forEach( friend =>{ // 'this' 就是 loop 的 'this' console.log( this.name + ' knows ' + friend ); });}
我不喜欢 APIs 中像一些普通函数的参数那样使用 this :
JavaScript 代码:
beforeEach(function () { this.addMatchers({ toBeInRange: function (start, end) { ... } }); });
箭头函数将一个隐式的参数转变为显式的,使得行为更为明确和兼容。
JavaScript 代码:
beforeEach(api => { api.addMatchers({ toBeInRange(start, end) { ... } });});
在 JavaScript 中,this 是一个相对难懂的特殊变量。因为它随处可用,而不仅仅是面向对象的编程中。本文将解释 this 是如何工作的,以及它可能导致问题的地方,并在文章的给出最佳实践。
为了方便理解 this ,最好的方式是根据使用 this 的位置划分三种类型:
- 在函数内部: this 是一个额外的隐含的参数。
- 在函数外部(顶级作用域中): this 在浏览器中指向全局对象;在 Node.jS 中指向 模块(module) 的接口(exports)。
- 在传递给 eval() 的字符串中: eval() 如果是被直接调用, this 指的是当前对象;如果是被间接调用,this 指的是全局对象。
我们来看看每个类别。
1.函数内部的 this
这是 this 最常用的使用场景,因为 JavaScript 中,以三种不同的角色代表了所有的可调用的结构形式:
- 真正函数( this 在松散模式下是全局对象,严格模式下是 undefined )
- 构造函数( this 指向刚创建的实例 )
- 方法: (this 指向方法调用的接受对象 )
在函数中,this 可以理解为一个额外隐含的参数。
1.1 真正函数中的 this
在真正函数中,this 的值取决于函数所处的模式:
- 松散模式(Sloppy mode): this 指向全局对象 (浏览器中就是 window )。
JavaScript 代码:
function sloppyFunc() { console.log(this === window); // true}sloppyFunc();
- 严格模式:this 的值为 undefined 。
JavaScript 代码:
function strictFunc() { 'use strict'; console.log(this === undefined); // true}strictFunc();
也就是说,这是一个默认值( window 或 undefined )的隐式参数。但是,您可以通过 call() 或者 apply() 来调用函数,并明确的指定 this 的值。
JavaScript 代码:
function func(arg1, arg2) { console.log(this); // a console.log(arg1); // b console.log(arg2); // c}func.call('a', 'b', 'c'); // (this, arg1, arg2)func.apply('a', ['b', 'c']); // (this, arrayWithArgs)
1.2 构造函数中的 this
如果你通过 new 操作符来调用函数,则函数将成为构造函数。该操作符创建一个新的对象,并通过 this 把它传递给构造函数:
JavaScript 代码:
var savedThis;function Constr() { savedThis = this;}var inst = new Constr();console.log(savedThis === inst); // true
new 操作符在JavaScript中实现,大致如下(更精确的实现稍微复杂一点):
JavaScript 代码:
function newOperator(Constr, arrayWithArgs) { var thisValue = Object.create(Constr.prototype); Constr.apply(thisValue, arrayWithArgs); return thisValue;}
1.3 方法中的 this
在方法中,所有的事情都和传统的面向对象语言类似: this 指向接受对象,即方法被哪个对象调用。
JavaScript 代码:
var obj = { method: function () { console.log(this === obj); // true }}obj.method();
2.顶级作用域中的 this
在浏览器环境中,顶级作用域是全局作用域, this 指向 全局对象(诸如 window 之类):
HTML 代码:
在 Node.js 中,你通常在 模块(module) 中执行代码。因此,顶级作用域是一个指定模块的作用域(module scope)。
JavaScript 代码:
// `global` (not `window`) refers to global object:console.log(Math === global.Math); // true// this doesn’t refer to the global object: console.log(this !== global); // true // this refers to a module’s exports: console.log(this === module.exports); // true
3.eval() 中的 this
eval() 既可以被直接调用(通过一个真正函数调用),也可以被间接调用(通过另一些方式)。以下是具体解释。
如果 eavl() 被间接调用, this 指向 全局对象,在控制台中输入:
JavaScript 代码:
> (0,eval)('this === window')true
否者,如果 eval() 被直接调用,那么 this 指向 eval() 所处的执行环境。例如:
JavaScript 代码:
// Real functionsfunction sloppyFunc() { console.log(eval('this') === window); // true}sloppyFunc(); function strictFunc() { 'use strict'; console.log(eval('this') === undefined); // true}strictFunc(); // Constructorsvar savedThis;function Constr() { savedThis = eval('this');}var inst = new Constr();console.log(savedThis === inst); // true // Methodsvar obj = { method: function () { console.log(eval('this') === obj); // true }}obj.method();
4.this 相关的陷阱
这里有3个和 this 有关的陷阱值得注意的。 记住,严格模式可以使得每种情况变得正常,因为在真正函数中 this 都会为 undefined ,当出错的时候会收到警告。
4.1 忘记使用 new 操作符
如果你调用构造函数却忘记使用了 new 操作符,那么你会意外的调用一个真正函数。因此, this 不会指向正确的值。在松散模式中,this 指向 window ,并且会创建全局变量:
JavaScript 代码:
function Point(x, y) { this.x = x; this.y = y;}var p = Point(7, 5); // 我们忘记了 new!console.log(p === undefined); // true // 全局变量已创建:console.log(x); // 7console.log(y); // 5
幸好,在严格模式下你会收到一条警告( this === undefined):
JavaScript 代码:
function Point(x, y) { 'use strict'; this.x = x; this.y = y;}var p = Point(7, 5);// TypeError: Cannot set property 'x' of undefined
4.2 获取方法不当
如果你获取的是方法的值(而非调用),你会将方法又转变为函数。调用这个值的结果是一个函数调用,而不是一个方法调用。当你将方法作为函数或方法调用的参数传递时,可能会发生这种情况。真实的例子包括 setTimeout() 和 注册处理程序。我将使用 callIt() 函数同步模拟这个用例:
JavaScript 代码:
/* 与 setTimeout() 和 setImmediate() 类似 */function callIt( func ){ func();}
如果你调用一个松散模式下的函数, this 指向全局对象,并且创建全局变量:
JavaScript 代码:
var counter = { count: 0, // 松散模式下 method inc: function () { this.count++; }} callIt(counter.inc); // 不会:console.log(counter.count); // 0 // 相反,一个全局变量已经被创建// (NaN 是 undefined 应用 ++ 后结果):console.log(count); // NaN
如果你调用严格模式下的函数,this 为 undefined , 代码也将会无效。但是会收到一个警告。
JavaScript 代码:
var counter = { count: 0, // 严格模式下 method inc: function () { 'use strict'; this.count++; }} callIt(counter.inc); // TypeError: Cannot read property 'count' of undefinedconsole.log(counter.count);
可以使用 bind() 开解决:
JavaScript 代码:
var counter = { count: 0, inc: function () { this.count++; }} callIt(counter.inc.bind(counter)); // It worked!console.log(counter.count); // 1
bind() 创建一个接受的 this 值为 counter 的新函数。
4.3 覆盖 this
当你在一个方法中使用一个真正函数时,很容易忘记前者有它自己的 this 值(即使真正的函数中没用显式的使用 this )。 因此,你不能从真正函数中的 this引用到方法的 this,因为它是被覆盖的。 我们来看一个事情出错的例子:
JavaScript 代码:
var obj = { name: 'Jane', friends: [ 'Tarzan', 'Cheeta' ], loop: function () { 'use strict'; this.friends.forEach( function (friend) { console.log(this.name+' knows '+friend); } ); }};obj.loop();// TypeError: Cannot read property 'name' of undefined
在上面例子中,this.name 失败,原因是函数的 this 为 undefined ,他与 loop() 方法内的 this 并不是同一个 this ,这里有 3 种解决方案。
解决方案1: that = this。将 this 分配给一个变量,使其不再被覆盖(另一个常用的变量名为 self)再使用它。
JavaScript 代码:
loop: function () { 'use strict'; var that = this; this.friends.forEach(function (friend) { console.log(that.name+' knows '+friend); });}
解决方案2:bind()。使用 bind() 来创建一个 this 常指向当前值的函数(在下面这个例子中是:方法的 this)。
JavaScript 代码:
loop : function(){ 'use strict'; this.friends.forEach(function( friend ){ console.log( this.name + ' knows ' + friend ); }.bind( this ));}
解决方案3:forEach 的第二个参数。该方法有第二个参数,它的值作为this传递给回调函数。
JavaScript 代码:
loop : function(){ 'use strict'; this.friends.forEach(function( friend ){ console.log( this.name + ' knows ' + friend ); }, this );}
5.最佳实践
概念上来说,我认为真正函数并不具有它们自己的 this ,并且想到前面提到的解决方案就是保持这种错觉。ECMAScript 6 通过箭头函数来支持保持 this – 函数没有其自己的 this 值。在箭头函数中,你可以无忧无虑的使用 this ,因为不会被覆盖。
JavaScript 代码:
loop : function(){ 'use strict'; // forEach 的参数就是箭头函数 this.friends.forEach( friend =>{ // 'this' 就是 loop 的 'this' console.log( this.name + ' knows ' + friend ); });}
我不喜欢 APIs 中像一些普通函数的参数那样使用 this :
JavaScript 代码:
beforeEach(function () { this.addMatchers({ toBeInRange: function (start, end) { ... } }); });
箭头函数将一个隐式的参数转变为显式的,使得行为更为明确和兼容。
JavaScript 代码:
beforeEach(api => { api.addMatchers({ toBeInRange(start, end) { ... } });});