重要的事情先講三遍:誰調(diào)用this,this指向誰!誰調(diào)用this,this指向誰!誰調(diào)用this,this指向誰!
(1)this由test調(diào)用,this指向window,結果this.m的值為100。
window.m=100;//window.m=100等價于 this.m=100
function test(){
alert(this.m);
}
window.test();//test()等同于window.test()
(2)this由test調(diào)用,test由obj調(diào)用,因此this.m的值就為obj.m的值,為100.
this.m=1000;
var obj = {
m:100,
test:function(){
alert(this.m);
}
}
obj.test();
(3)return function()已經(jīng)將自己從obj中拋出來了,此時它指向外面的window,因此this.m的值為1000
this.m=1000;
var obj = {
m:100,
test:function(){
alert(this.m);
//閉包
return function(){
alert(this.m);
}
}
};
obj.test()();
obj.test()一個括號調(diào)用test()的函數(shù),但不包括return后的函數(shù);
obj.test()()兩個括號可以執(zhí)行到return后的函數(shù)。
也可以寫成:(obj.test())();
或者:var t = obj.test(); window.t();
(4)當在外部調(diào)用函數(shù)test()時,this指向window,就會執(zhí)行color:"green"的代碼。點擊按鈕時,是button調(diào)用test()函數(shù),因此this指向button。
html
<input type="button" id="test" value="點擊一下" style="color:red;">
JavaScript
var style = {
color:"green"
}
function test(){
alert(this.style.color);//this指向button
}
document.getElementById("test").onclick=test;
window.test();
(5)結果為1,p調(diào)用了geta(),geta()被掛在test原型上,p又是test聲明出來的,因此p應該找到test()下的this.a 與外面的1000無關。
this.a=1000;
function test(){
this.a=1;
}
test.prototype.geta = function() {
return this.a;
};
var p = new test;
console.log(p.geta());//1
(6)結果為1,p是test()聲明的,因此直接執(zhí)行test()函數(shù),與test.prototype.a = 100;無影響
function test(){
this.a=1;
}
test.prototype.a = 100;
var p = new test;
console.log(p);//1
(7)結果仍然為1,因為this的主動權大,因為它在構造函數(shù)中。
function test(){
this.a=1;
}
test.prototype.a = 100;
var p = new test;
console.log(p.a);//1
內(nèi)容為JavaScript關于this的小總結,如果有不正確的地方歡迎小伙伴們指正哦~