this

作者:李挺
链接:https://www.zhihu.com/question/19636194/answer/123274198
来源:知乎
著作权归作者所有,转载请联系作者获得授权。

关于 this 的描述,曾经在 stackoverflow 上看到了一篇回答写的非常详尽,下面的文字是一个简单的总结:

(一)定义:是一个关键字,用来计算当前执行上下文中 ThisBinding 的值。
  • 定义推断:作为一个关键字,既不是变量,又不是对象属性,因此不能给 this 赋值,而且 this 也不受作用域的限制,嵌套函数中的 this 不会从调用它的函数中继承 this。

(二)ThisBinding 的值(this 的计算结果):
  1. 全局执行上下文中——global 对象
  2. eval() 中
    • 如果 eval() 是直接调用,那么 Thisbinding 的值取决于 eval() 所处的执行上下文;
    • 如果是间接调用,那么 ThisBinding 的值为 global 对象;【注1】
3. 函数中
    • 作为普通的函数调用,为 global(非严格模式下)或 undefined (严格模式下);
    • 作为某个对象的方法调用,那么 ThisBinding 的值就是这个对象;
    • 作为构造函数调用,ThisBinding 的值为所创建的新的空对象;【注2】
    • 间接调用下,有八种函数可以在参数中指定 ThisBinding 的值
Function.prototype.apply(thisArg, argArray);
Function.prototype.call(thisArg[, arg1[, arg2, ...]]);
Function.prototype.bind(thisArg[, arg1[, arg2, ...]]);
Array.prototype.every(callbackfn[, thisArg]);
Array.prototype.some(callbackfn[, thisArg]);
Array.prototype.forEach(callbackfn[, thisArg]);
Array.prototype.map(callbackfn[, thisArg]);
Array.prototype.filter(callbackfn[, thisArg]);
      • 在 Function.prototype 下的函数,thisArg 指定其主体函数中的 ThisBinding 值;(thisArg 不一定与 ThisBinding 相等【注3】)
      • 在 Array.prototype 下的函数,thisArg 指定 callbackfn 中 ThisBinding 的值。

注解:
    1. eval 是通过表达式计算得到的,那么此时,eval 调用称之为间接调用,eval 中的代码在全局环境下执行。(例如:
      var x = 'outer';
      (function(){
      var x = 'inner';
      eval('console.log("直接调用: " + x)');        // 直接调用: inner
      (1, eval)('console.log("间接调用: " + x)');   // 间接调用: outer
      })();
      
    2. 构造函数的调用细节:构造函数调用之前会自动创建一个新的空对象,构造函数作为这个新对象的方法进行调用,所以构造函数通过 this 就可以初始化这个新对象,最后,这个新对象作为构造函数调用表达式的值,构造函数的 prototype 属性作为新对象的原型。
    3. 如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动指向 global 对象,同时如果 thisArg 是原始值的话,那么 ThisBinding 的值原始值的包装对象。

引用:
    1. javascript - How does the "this" keyword work?
    2. (1,eval)('this') vs eval('this') in JavaScript?
    3. Function.prototype.apply(),Function.prototype.call(),Function.prototype.bind()
    4. 《JavaScript 权威指南》第六版
posted @ 2016-12-19 16:35  yasepix  阅读(196)  评论(0编辑  收藏  举报