关于javascript中this的trick

看以下对象定义:

'use strict'
var jane = {
    name : ‘Jane’,
    display : function(){
        retrun 'Person named ' + this.name;
    }
};

如许能一般挪用

jane.display();

下面的挪用会失足:

var func = jane.display;
func()
TypeError: Cannot read property ‘name’ of undefined

由于,this指向已转变,准确的体式格局以下:

var func2 = jane.display.bind(jane);
func2()
‘Penson named Jane’

一切函数都有其特别的this变量,以下面的forEach

var jane = {
    name : 'Jane',
    friends: ['Tarzan', 'Cheeta'],
    sayHiToFriends: function(){
        'use strict';
        this.friends.forEach(function(friend) {
            // 'this' is undefined here
            console.log(this.name + ' says hi to '+ friend);
        });
    }
}   

挪用sayHiToFriends会发生一个毛病:

jane.sayHiToFriends()
TypeError: Cannot read property ‘name’ of undefined

解决方案一:将this保存在差别的变量中

var jane = {
    name : 'Jane',
    friends: ['Tarzan', 'Cheeta'],
    sayHiToFriends: function(){
        'use strict';
        var that = this;
        this.friends.forEach(function(friend) {
            console.log(that.name + ' says hi to '+ friend);
        });
    }
}  

解决方案二:应用forEach的第二个参数,它能够给this指定一个值

var jane = {
    name : 'Jane',
    friends: ['Tarzan', 'Cheeta'],
    sayHiToFriends: function(){
        'use strict';
        this.friends.forEach(function(friend) {
            console.log(this.name + ' says hi to '+ friend);
        }, this);
    }
}  
    原文作者:zhoutk
    原文地址: https://segmentfault.com/a/1190000004756134
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞