1、在对象的方法中如果有this,那么该对象调用此方法时,this表示这个对象:
var obj1 = {attr:"a Obj",
aboutMe:function(){
console.log(this.attr);
}
}
在控制台中实验:
该方法被赋值给其他变量时,this指向全局变量:
var obj2 = {
attr:”a Obj”,
aboutMe:function(){
if(this.attr) console.log(“still have thie attribute ‘attr’!”);
if(this === window)
console.log(“equal to window!!!”)
}
}
2、构造函数中的this指向构造的实例:
要有new 关键字!!!
var test = function(){
console.log(this);
};
test(); //window
new test(); // test()
一段比较绕的代码:
var test2 = function(){
console.log(this);
return function(){
console.log(this);
}
};
测试:
在控制台中测试test2()
;、test2()();
和new test2();
注:图中的红色数字表示第几个console.log
的输出