JavaScript 中 this 的工作原理以及注意事项

开发 前端
在JavaScript中,this 的概念比较复杂。除了在面向对象编程中,this 还是随处可用的。这篇文章介绍了this 的工作原理,它会造成什么样的问题以及this 的相关例子。

在JavaScript中,this 的概念比较复杂。除了在面向对象编程中,this 还是随处可用的。这篇文章介绍了this 的工作原理,它会造成什么样的问题以及this 的相关例子。 要根据this 所在的位置来理解它,情况大概可以分为3种:

  1. 在函数中:this 通常是一个隐含的参数。

  2. 在函数外(***作用域中):在浏览器中this 指的是全局对象;在Node.js中指的是模块(module)的导出(exports)。

  3. 传递到eval()中的字符串:如果eval()是被直接调用的,this 指的是当前对象;如果eval()是被间接调用的,this 就是指全局对象。

对这几个分类,我们做了相应的测试:

  1. 在函数中的this

    函数基本可以代表JS中所有可被调用的结构,所以这是也最常见的使用this 的场景,而函数又能被子分为下列三种角色:

    1.1  在实函数中的this

    在实函数中,this 的值是取决于它所处的上下文的模式

    • Sloppy模式:this 指的是全局对象(在浏览器中就是window)。

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

Strict模式:this 的值是undefined。

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

this 是函数的隐含参数,所以它的值总是相同的。不过你是可以通过使用call()或者apply()的方法显示地定义好this的值的。

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

1.2  构造器中的this

你可以通过new 将一个函数当做一个构造器来使用。new 操作创建了一个新的对象,并将这个对象通过this 传入构造器中。

  1. var savedThis;  
  2. function Constr() {  
  3.     savedThis = this;  
  4. }  
  5. var inst = new Constr();  
  6. console.log(savedThis === inst); // true  

JS中new 操作的实现原理大概如下面的代码所示(更准确的实现请看这里,这个实现也比较复杂一些):

  1. function newOperator(Constr, arrayWithArgs) {  
  2.     var thisValue = Object.create(Constr.prototype);  
  3.     Constr.apply(thisValue, arrayWithArgs);  
  4.     return thisValue;  
  5. }  

1.3  方法中的this

在方法中this 的用法更倾向于传统的面向对象语言:this 指向的接收方,也就是包含有这个方法的对象。

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

实函数

  • 构造器

方法

2. 作用域中的this

在浏览器中,作用域就是全局作用域,this 指的就是这个全局对象(就像window):

  1. <script>  
  2.     console.log(this === window); // true  
  3. </script>  

在Node.js中,你通常都是在module中执行函数的。因此,***作用域是个很特别的模块作用域(module scope):

  1. // `global` (not `window`) refers to global object:  
  2. console.log(Math === global.Math); // true  
  3.  
  4. // `this` doesn’t refer to the global object:  
  5. console.log(this !== global); // true  
  6. // `this` refers to a module’s exports:  
  7. console.log(this === module.exports); // true  

3. eval()中的this

eval()可以被直接(通过调用这个函数名&#8217;eval&#8217;)或者间接(通过别的方式调用,比如call())地调用。要了解更多细节,请看这里

  1. // Real functions  
  2. function sloppyFunc() {  
  3.     console.log(eval(&#039;this&#039;) === window); // true  
  4. }  
  5. sloppyFunc();  
  6.  
  7. function strictFunc() {  
  8.     &#039;use strict&#039;;  
  9.     console.log(eval(&#039;this&#039;) === undefined); // true  
  10. }  
  11. strictFunc();  
  12.  
  13. // Constructors  
  14. var savedThis;  
  15. function Constr() {  
  16.     savedThis = eval(&#039;this&#039;);  
  17. }  
  18. var inst = new Constr();  
  19. console.log(savedThis === inst); // true  
  20.  
  21. // Methods  
  22. var obj = {  
  23.     method: function () {  
  24.         console.log(eval(&#039;this&#039;) === obj); // true  
  25.     }  
  26. }  
  27. obj.method();  

4.与this有关的陷阱

你要小心下面将介绍的3个和this 有关的陷阱。要注意,在下面的例子中,使用Strict模式(strict mode)都能提高代码的安全性。由于在实函数中,this 的值是undefined,当出现问题的时候,你会得到警告。

4.1  忘记使用new

如果你不是使用new来调用构造器,那其实你就是在使用一个实函数。因此this就不会是你预期的值。在Sloppy模式中,this 指向的就是window 而你将会创建全局变量:

  1. function Point(x, y) {  
  2.     this.x = x;  
  3.     this.y = y;  
  4. }  
  5. var p = Point(7, 5); // we forgot new!  
  6. console.log(p === undefined); // true  
  7.  
  8. // Global variables have been created:  
  9. console.log(x); // 7  
  10. console.log(y); // 5  

不过如果使用的是strict模式,那你还是会得到警告(this===undefined):

  1. function Point(x, y) {  
  2.     &#039;use strict&#039;;  
  3.     this.x = x;  
  4.     this.y = y;  
  5. }  
  6. var p = Point(7, 5);  
  7. // TypeError: Cannot set property &#039;x&#039; of undefined  

4.2 不恰当地使用方法

如果你直接取得一个方法的值(不是调用它),你就是把这个方法当做函数在用。当你要将一个方法当做一个参数传入一个函数或者一个调用方法中,你很可能会这么做。setTimeout()和注册事件句柄(event handlers)就是这种情况。我将会使用callIt()方法来模拟这个场景:

  1. /** Similar to setTimeout() and setImmediate() */ 
  2. function callIt(func) {  
  3.     func();  
  4. }  

如果你是在Sloppy模式下将一个方法当做函数来调用,*this*指向的就是全局对象,所以之后创建的都会是全局的变量。

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

如果你是在Strict模式下这么做的话,this是undefined的,你还是得不到想要的结果,不过至少你会得到一句警告:

  1. var counter = {  
  2.     count: 0,  
  3.     // Strict-mode method  
  4.     inc: function () {  
  5.         &#039;use strict&#039;;  
  6.         this.count++;  
  7.     }  
  8. }  
  9. callIt(counter.inc);  
  10.  
  11. // TypeError: Cannot read property &#039;count&#039; of undefined  
  12. console.log(counter.count);  

要想得到预期的结果,可以使用bind()

  1. var counter = {  
  2.     count: 0,  
  3.     inc: function () {  
  4.         this.count++;  
  5.     }  
  6. }  
  7. callIt(counter.inc.bind(counter));  
  8. // It worked!  
  9. console.log(counter.count); // 1  

bind()又创建了一个总是能将this的值设置为counter 的函数。

4.3 隐藏this

当你在方法中使用函数的时候,常常会忽略了函数是有自己的this 的。这个this 又有别于方法,因此你不能把这两个this 混在一起使用。具体的请看下面这段代码:

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

上面的例子里函数中的this.name 不能使用,因为函数的this 的值是undefined,这和方法loop()中的this 不一样。下面提供了三种思路来解决这个问题:

  • that=this,将this 赋值到一个变量上,这样就把this 显性地表现出来了(除了thatself 也是个很常见的用于存放this的变量名),之后就使用那个变量:
  1. loop: function () {  
  2.     &#039;use strict&#039;;  
  3.     var that = this;  
  4.     this.friends.forEach(function (friend) {  
  5.         console.log(that.name+&#039; knows &#039;+friend);  
  6.     });  
  7. }  
  • bind()。使用bind()来创建一个函数,这个函数的this 总是存有你想要传递的值(下面这个例子中,方法的this):
  1. loop: function () {  
  2.     &#039;use strict&#039;;  
  3.     this.friends.forEach(function (friend) {  
  4.         console.log(this.name+&#039; knows &#039;+friend);  
  5.     }.bind(this));  
  6. }  
  • 用forEach的第二个参数。forEach的第二个参数会被传入回调函数中,作为回调函数的this 来使用。

5. ***实践

理论上,我认为实函数并没有属于自己的this,而上述的解决方案也是按照这个思想的。ECMAScript 6是用箭头函数(arrow function)来实现这个效果的,箭头函数就是没有自己的this 的函数。在这样的函数中你可以随便使用this,也不用担心有没有隐式的存在。

  1. loop: function () {  
  2.     &#039;use strict&#039;;  
  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+&#039; knows &#039;+friend);  
  7.     });  
  8. }  

我不喜欢有些API把this 当做实函数的一个附加参数:

  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. });  

原文链接: 2ality   翻译: 伯乐在线 - kmokidd

译文链接: http://blog.jobbole.com/67347/

责任编辑:林师授 来源: 伯乐在线
相关推荐

2021-09-28 08:59:40

UPS蓄电池电源

2017-04-06 09:49:55

Hive注意事项优化

2018-03-06 10:14:55

程序员找工作经验教训

2011-07-21 14:28:17

MySQL事务事务保存点

2010-08-17 10:42:37

NAT路由器

2011-05-26 11:22:04

SEO

2011-03-31 13:58:34

cactinagios

2012-06-13 02:02:43

ServletJavaJSP

2011-09-01 09:45:01

Ubuntu上安装Mo

2013-07-16 10:49:17

游戏开发手机游戏

2021-10-25 16:25:07

模型人工智能计算

2020-11-13 07:11:23

MySQL复制日志

2009-12-30 10:12:30

MPLS VPN

2009-12-15 17:47:17

VSIP

2011-07-21 15:20:31

iPhone SDK 多线程

2010-11-26 16:27:01

MySQL使用变量

2011-09-26 11:02:10

2023-01-14 09:49:11

2020-10-20 14:05:48

用户需求分析IT

2021-11-16 10:35:59

云计算云计算环境云应用
点赞
收藏

51CTO技术栈公众号