JavaScript中this的运行机制及爬坑指南

开发 前端
在 JavaScript 中,this 这个特殊的变量是相对比较复杂的,因为 this 不仅仅用在面向对象环境中,在其他任何地方也是可用的。 本篇博文中会解释 this 是如何工作的以及使用中可能导致问题的地方,最后奉上最佳实践。

[[222693]]

在 JavaScript 中,this 这个特殊的变量是相对比较复杂的,因为 this 不仅仅用在面向对象环境中,在其他任何地方也是可用的。 本篇博文中会解释 this 是如何工作的以及使用中可能导致问题的地方,***奉上***实践。

为了更好地理解 this,将 this 使用的场景分成三类:

  • 在函数内部 this 一个额外的,通常是隐含的参数。
  • 在函数外部(***作用域中): 这指的是浏览器中的全局对象或者 Node.js 中一个模块的输出。
  • 在传递给eval()的字符串中: eval() 或者获取 this 当前值值,或者将其设置为全局对象,取决于 this 是直接调用还是间接调用。

我们来看看每个类别。

this 在函数中

这是最常用的 this 使用方式,函数通过扮演三种不同的角色来表示 JavaScript 中的所有可调用结构体:

  • 普通函数(this 在非严格模式下为全局对象,在严格模式下为undefined)
  • 构造函数(this 指向新创建的实例)
  • 方法(this 是指方法调用的接收者)

在函数中,this 通常被认为是一个额外的,隐含的参数。

this 在普通函数中

在普通函数中,this 的值取决于模式:

非严格模式: this 是指向全局对象 (在浏览器中为window对象)。

 

  1. function sloppyFunc() {  
  2.     console.log(this === window); // true  
  3.  
  4. sloppyFunc(); 

 

严格模式: this 的值为 undefined。

 

  1. function strictFunc() {  
  2.     'use strict' 
  3.     console.log(this === undefined); // true  
  4.  
  5. strictFunc(); 

 

也就是说,this 是一个设定了默认值(window或undefined)的隐式参数。 但是,可以通过 call() 或 apply() 进行函数调用,并明确指定this的值:

 

  1. function func(arg1, arg2) {  
  2.     console.log(this); // a  
  3.     console.log(arg1); // b  
  4.     console.log(arg2); // c  
  5.  
  6. func.call('a''b''c'); // (this, arg1, arg2)  
  7. func.apply('a', ['b''c']); // (this, arrayWithArgs) 

 

this 在构造函数中

如果通过new运算符调用函数,则函数将成为构造函数。 该运算符创建一个新的对象,并通过this传递给构造函数:

 

  1. var savedThis;  
  2. function Constr() { 
  3.     savedThis = this;  
  4.  
  5. var inst = new Constr();  
  6. console.log(savedThis === inst); // true  
  7. 在JavaScript中实现,new运算符大致如下所示(更精确的实现稍微复杂一点):  
  8. function newOperator(Constr, arrayWithArgs) {  
  9.     var thisValue = Object.create(Constr.prototype);  
  10.     Constr.apply(thisValue, arrayWithArgs);  
  11.     return thisValue;  

 

this 在方法中

在方法中,类似于传统的面向对象的语言:this指向接受者,方法被调用的对象。

 

  1. var obj = {  
  2.     method: function () {  
  3.         console.log(this === obj); // true  
  4.     }  
  5.  
  6. obj.method(); 

 

this 在***作用域中

在浏览器中,顶层作用域是全局作用域,它指向 global object(如window):

 

  1. console.log(this === window); // true 

在Node.js中,通常在模块中执行代码。 因此,***作用域是一个特殊的模块作用域:

 

  1. // `global` (不是 `window`) 指全局对象:  
  2. console.log(Math === global.Math); // true  
  3.  
  4. // `this` 不指向全局对象:  
  5. console.log(this !== global); // true  
  6. // `this` refers to a module’s exports:  
  7. console.log(this === module.exports); // true 

 

this 在 eval() 中

eval() 可以被直接(通过真正的函数调用)或间接(通过其他方式)调用。

如果间接调用evaleval() ,则this指向全局对象:

 

  1. (0,eval)('this === window' 
  2. true 

 

否则,如果直接调用eval() ,则this与eval()的环境中保持一致。 例如:

 

  1. // 普通函数  
  2. function sloppyFunc() {  
  3.     console.log(eval('this') === window); // true  
  4.  
  5. sloppyFunc();  
  6.  
  7. function strictFunc() {  
  8.     'use strict' 
  9.     console.log(eval('this') === undefined); // true  
  10.  
  11. strictFunc();  
  12.  
  13. // 构造器  
  14. var savedThis;  
  15. function Constr() {  
  16.     savedThis = eval('this');  
  17.  
  18. var inst = new Constr();  
  19. console.log(savedThis === inst); // true   
  20.  
  21. // 方法  
  22. var obj = {  
  23.     method: function () {  
  24.         console.log(eval('this') === obj); // true  
  25.     }  
  26.  
  27. obj.method(); 

 

与this相关的陷阱

有三个你需要知道的与this相关的陷阱。请注意,在各种情况下,严格模式更安全,因为this在普通函数中为undefined,并且会在出现问题时警告。

陷阱:忘记new操作符

如果你调用一个构造函数时忘记了new操作符,那么你意外地将this用在一个普通的函数。this会没有正确的值。 在非严格模式下,this指向window对象,你将创建全局变量:

 

  1. function Point(x, y) {  
  2.     this.x = x;  
  3.     this.y = y;  
  4.  
  5. var p = Point(7, 5); // 忘记new!  
  6. console.log(p === undefined); // true   
  7.  
  8. // 创建了全局变量:  
  9. console.log(x); // 7  
  10. console.log(y); // 5  
  11. 幸运的是,在严格模式下会得到警告(this === undefined):  
  12. function Point(x, y) {  
  13.     'use strict' 
  14.     this.x = x;  
  15.     this.y = y;  
  16.  
  17. var p = Point(7, 5);  
  18. // TypeError: Cannot set property 'x' of undefined 

 

陷阱:不正确地提取方法

如果获取方法的值(不是调用它),则可以将该方法转换为函数。 调用该值将导致函数调用,而不是方法调用。 当将方法作为函数或方法调用的参数传递时,可能会发生这种提取。 实际例子包括setTimeout()和事件注册处理程序。 我将使用函数callItt() 来模拟此用例:

 

  1. /**类似setTimeout() 和 setImmediate() */  
  2. function callIt(func) {  
  3.     func();  

 

如果在非严格模式下把一个方法作为函数来调用,那么this将指向全局对象并创建全局变量:

 

  1. var counter = { 
  2.     count: 0, 
  3.     // Sloppy-mode method 
  4.     inc: function () { 
  5.         this.count++; 
  6.     } 
  7. callIt(counter.inc); 
  8. // Didn’t work
  9. console.log(counter.count); // 0 
  10. // Instead, a global variable has been created 
  11. // (NaN is result of applying ++ to undefined): 
  12. console.log(count); // NaN 

 

如果在严格模式下把一个方法作为函数来调用,this为undefined。 同时会得到一个警告:

 

  1. var counter = {  
  2.     count: 0,  
  3.     // Strict-mode method  
  4.     inc: function () {  
  5.         'use strict' 
  6.         this.count++;  
  7.     }  
  8.  
  9.  
  10. callIt(counter.inc);  
  11. // TypeError: Cannot read property 'count' of undefined  
  12. console.log(counter.count);  
  13. 修正方法是使用bind():  
  14. var counter = {  
  15.     count: 0,  
  16.     inc: function () {  
  17.         this.count++;  
  18.     }  
  19.  
  20. callIt(counter.inc.bind(counter));  
  21.  
  22. // 成功了!  
  23. console.log(counter.count); // 1 

 

bind()创建了一个新的函数,它总是能得到一个指向counter的this。

陷阱:shadowing this

当在一个方法中使用普通函数时,很容易忘记前者具有其自己this(即使其不需要this)。 因此,你不能从前者引用该方法的this,因为该this会被遮蔽。 让我们看看出现问题的例子:

 

  1. var obj = {  
  2.     name'Jane' 
  3.     friends: [ 'Tarzan''Cheeta' ],  
  4.     loop: function () {  
  5.         'use strict' 
  6.         this.friends.forEach(  
  7.             function (friend) {  
  8.                 console.log(this.name+' knows '+friend);  
  9.             }  
  10.         );  
  11.     }  
  12. };  
  13. obj.loop();  
  14. // TypeError: Cannot read property 'name' of undefined 

在前面的例子中,获取this.name失败,因为函数的this个是undefined,它与方法loop()的不同。 有三种方法可以修正this。

修正1: that = this。 将它分配给一个没有被遮蔽的变量(另一个流行名称是self)并使用该变量。

 

  1. loop: function () {  
  2.     'use strict' 
  3.     var that = this;  
  4.     this.friends.forEach(function (friend) {  
  5.         console.log(that.name+' knows '+friend);  
  6.     });  

 

修正2: bind()。 使用bind()来创建一个this总是指向正确值的函数(在下面的例子中该方法的this)。

 

  1. loop: function () {  
  2.     'use strict' 
  3.     this.friends.forEach(function (friend) {  
  4.         console.log(this.name+' knows '+friend);  
  5.     }.bind(this));  

 

修正3: forEach的第二个参数。 此方法具有第二个参数,this值将作为此值传递给回调函数。

 

  1. loop: function () {  
  2.     'use strict' 
  3.     this.friends.forEach(function (friend) {  
  4.         console.log(this.name+' knows '+friend);  
  5.     }, this);  

 

***实践

从概念上讲,我认为普通函数没有它自己的this,并且想到上述修复是为了保持这种想法。 ECMAScript 6通过箭头函数支持这种方法 - 没有它们自己的this。 在这样的函数里面,你可以自由使用this,因为不会被屏蔽:

 

  1. loop: function () {  
  2.     'use strict' 
  3.     // The parameter of forEach() is an arrow function  
  4.     this.friends.forEach(friend => {  
  5.         // `this` is loop’s `this`  
  6.         console.log(this.name+' knows '+friend);  
  7.     });  

 

我不喜欢使用this作为普通函数的附加参数的API:

 

  1. beforeEach(function () {  
  2.     this.addMatchers({  
  3.         toBeInRange: function (start, end) {  
  4.             ...  
  5.         }  
  6.     });  
  7. }); 

 

将这样的隐含参数变成明确的参数使得事情更加明显,并且与箭头函数兼容。

 

  1. beforeEach(api => {  
  2.     api.addMatchers({  
  3.         toBeInRange(start, end) {  
  4.             ...  
  5.         }  
  6.     });  
  7. });  

 

责任编辑:庞桂玉 来源: 前端大全
相关推荐

2019-10-11 09:00:00

JavaScriptEvent Loop前端

2015-11-20 11:20:54

js开发

2022-02-11 23:11:09

Kubernetes集群容器化

2019-05-10 14:00:21

小程序运行机制前端

2019-08-15 10:17:16

Webpack运行浏览器

2009-02-03 14:00:20

PHP运行PHP调用PHP原理

2009-12-11 10:52:37

PHP运行机制

2010-02-01 17:19:30

C++运行机制

2010-09-28 11:05:49

jQuery

2015-11-16 11:17:30

PHP底层运行机制原理

2010-05-06 17:54:54

Oracle锁

2018-12-26 16:30:09

SQL Server内部运行机制数据库

2010-01-05 16:10:21

.NET Framew

2023-05-26 08:01:01

FacebookVelox机制

2012-03-06 10:22:00

程序

2010-02-23 10:15:22

WCF运行机制

2016-12-14 14:41:20

Hello World程序运行机制

2016-12-13 14:12:25

程序机制

2009-10-22 17:10:04

CLR和JRE运行机制

2013-05-08 12:42:39

HTTP协议IIS原理ASP.NET
点赞
收藏

51CTO技术栈公众号