javascript中this用法:1、使用this指代全局對象;2、使用this指代上級對象;3、使用this指代new出的對象;4、使用this指代第一個參數(shù)。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版,DELL G3電腦。
javascript中this用法:
1、在一般函數(shù)方法中使用 this 指代全局對象
function test(){ this.x = 1; alert(this.x); } test(); // 1
2、作為對象方法調(diào)用,this 指代上級對象
function test(){ alert(this.x); } var o = {}; o.x = 1; o.m = test; o.m(); // 1
3、作為構(gòu)造函數(shù)調(diào)用,this 指代new 出的對象
function test(){ this.x = 1; } var o = new test(); alert(o.x); // 1 //運(yùn)行結(jié)果為1。為了表明這時this不是全局對象,我對代碼做一些改變: var x = 2; function test(){ this.x = 1; } var o = new test(); alert(x); //2
4、apply 調(diào)用 ,apply方法作用是改變函數(shù)的調(diào)用對象,此方法的第一個參數(shù)為改變后調(diào)用這個函數(shù)的對象,this指代第一個參數(shù)
var x = 0; function test(){ alert(this.x); } var o={}; o.x = 1; o.m = test; o.m.apply(); //0 //apply()的參數(shù)為空時,默認(rèn)調(diào)用全局對象。因此,這時的運(yùn)行結(jié)果為0,證明this指的是全局對象。如果把最后一行代碼修改為 o.m.apply(o); //1
相關(guān)免費(fèi)學(xué)習(xí)推薦:javascript(視頻)