码迷,mamicode.com
首页 > 其他好文 > 详细

方法中的函数会掩盖this,解决办法!

时间:2017-05-19 23:58:52      阅读:351      评论:0      收藏:0      [点我收藏+]

标签:on()   ons   for   win   style   class   javascrip   code   obj   

要知道在javascript中this是种很神奇的东西,但是有时候也很淘气;

如下:

<script>
    var obj = {
        name: tqt,
        friends: [shangs, lisi],
        sayHello: function() {
            this.friends.forEach(function(friend){
                console.log(this.name +  say hello to  + friend);
            });
        },
    }
    obj.sayHello();
    //say hello to shangs
    //say hello to lisi
</script>

此时this已经不再指向obj了所以不会有name属性;(this现在指向window,太淘气了!)

对于这种情况解决办法如下:

方法一: 

<script>
    var obj = {
        name: tqt,
        friends: [shangs, lisi],
        sayHello: function() {
            var that = this;
            this.friends.forEach(function(friend){
                console.log(that.name +  say hello to  + friend);
            });
        },
    }
    obj.sayHello();
    //tqt say hello to shangs
    //tqt say hello to lisi
</script>

方法二:

<script>
    var obj = {
        name: tqt,
        friends: [shangs, lisi],
        sayHello: function() {
            this.friends.forEach(function(friend){
                console.log(this.name +  say hello to  + friend);
            }.bind(this));
        },
    }
    obj.sayHello();
    //tqt say hello to shangs
    //tqt say hello to lisi
</script>

方法三:

<script>
    var obj = {
        name: tqt,
        friends: [shangs, lisi],
        sayHello: function() {
            this.friends.forEach(function(friend){
                console.log(this.name +  say hello to  + friend);
            }, this);
        },
    }
    obj.sayHello();
    //tqt say hello to shangs
    //tqt say hello to lisi
</script>

 

方法中的函数会掩盖this,解决办法!

标签:on()   ons   for   win   style   class   javascrip   code   obj   

原文地址:http://www.cnblogs.com/tqt--0812/p/6880491.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!