javascript内部函数this指向问题

来源:互联网 发布:unity3d打不开 编辑:程序博客网 时间:2024/05/22 04:51
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