要知道在javascript中this是種很神奇的東西,可是有時候也很淘氣;javascript
以下:java
<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,太淘氣了!)this
對於這種狀況解決辦法以下:spa
方法一: code
<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>
方法二:blog
<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>
方法三:ip
<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>