作家
登录

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

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

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。

    修改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,因为不会被樊篱:


      推荐阅读

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

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


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

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

    关键词: 探索发现

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

    网友点评
    自媒体专栏

    评论

    热度

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