JS 初学者总是对 this 关键字感到困惑,因为与其他现代编程语言相比,JS 中的这this关键字有点棘手。 “this” 一般是表示当前所在的对象,但是事情并没有像它应该的那样发生。JS中的this关键字由函数的调用者决定,谁调用就this就指向哪个。如果找不到调用者,this将指向windows对象。
来几个粟子
第一个例子很简单。 调用 test对象中的 func(),因此func() 中的'this'指向的是 test 对象,所以打印的 prop 是 test 中的 prop,即 42。
var test = {
prop: 42,
func: function(){
return this.prop;
},
};
console.log (test.func()); // 42
如果我们直接调用getFullname函数,第二个例子将打印出'David Jones',因为此时 this 找不到调用者,所以默认就为 window 对象,打印的 fullname 即是全局的。
var fullname = ‘David Jones’
var obj ={
fullname: ‘Colin Brown’,
prop:{
fullname:’Aurelio Deftch’,
getFullname: function(){
return this.fullname;
}
}
}
var test = obj.prop.getFullname
console.log(test()) // David Jones
obj.prop.getFullname() // ‘Aurelio Deftch’