1. 程式人生 > >方法中的函數會掩蓋this,解決辦法!

方法中的函數會掩蓋this,解決辦法!

say 屬性 ava var hang javascrip func java cti

要知道在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,解決辦法!