作家
登录

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

作者: 来源: 2018-03-16 08:43:31 阅读 我要评论

 
  • function newOperator(Constr, arrayWithArgs) {  
  •     var thisValue = Object.create(Constr.prototype);  
  •     Constr.apply(thisValue, arrayWithArgs);  
  •     return thisValue;  
  • 陷阱:shadowing this

    最佳实践

    this 在办法中

    在办法中,类似于传统的面向对象的说话:this指向接收者,办法被调用的对象。

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

    在Node.js中,平日在模块中履行代码。 是以,顶级感化域是一个特别的模块感化域:

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

    1. console.log(this === window); // true 
    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. // 构造器 

        推荐阅读

        重磅消息:微软 Service Fabric 正式开源

      有奖调研 | 人脸辨认功能在互联网行业认知度情况经由过程应用法度榜样级其余感知和洞察,为微办事带来编排和主动化的优势 微软的 Azure Service Fabric 的官方博客在2017.3.2>>>详细阅读


      本文标题:JavaScript中this的运行机制及爬坑指南

      地址:http://www.17bianji.com/lsqh/40750.html

    关键词: 探索发现

    乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

    网友点评
    自媒体专栏

    评论

    热度

    精彩导读
    栏目ID=71的表不存在(操作类型=0)