javascript內部函數this指向問題

var name = "clever coder";
 
var person = {
name : "foocoder",
hello : function(sth){
var sayhello = function(sth) {
console.log(this.name + " says " + sth);
};
sayhello(
}
 
person.hello("hello world");//clever coder says hello world
在內部函數中,this沒有按預想的綁定到外層函數對象上,而是綁定到了全局對象。這裏普遍被認爲是JavaScript語言的設計錯誤,因爲沒有人想讓內部函數中的this指向全局對象。一般的處理方式是將this作爲變量保存下來,一般約定爲that或者self:

var name = "clever coder";
var person = {
name : "foocoder",
hello : function(sth){
var that = this;
var sayhello = function(sth) {
console.log(that.name + " says " + sth);
};
sayhello(sth);
}
}
person.hello("hello world");//foocoder says hello world

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章