您的位置:首页 > Web前端 > JavaScript

javascript中的this

2016-01-22 23:49 666 查看
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
的输出

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: