JS中this的四種用法
1.在一般函數方法中使用 this 指代全局對象
1
2
3
4
5
|
function test(){ this .x
= 1; alert( this .x); } test(); //
1 |
2.作爲對象方法調用,this 指代上級對象
function test(){ alert(this.x); } var o = {}; o.x = 1; o.m = test; o.m(); // 1
3.作爲構造函數調用,this 指代new 出的對象
function test(){ this.x = 1; } var o = new test(); alert(o.x); // 1 //運行結果爲1。爲了表明這時this不是全局對象,我對代碼做一些改變: var x = 2; function test(){ this.x = 1; } var o = new test(); alert(x); //2
4.apply 調用 ,apply方法作用是改變函數的調用對象,此方法的第一個參數爲改變後調用這個函數的對象,this指代第一個參數
var x = 0; function test(){ alert(this.x); } var o={}; o.x = 1; o.m = test; o.m.apply(); //0 //apply()的參數爲空時,默認調用全局對象。因此,這時的運行結果爲0,證明this指的是全局對象。如果把最後一行代碼修改爲 o.m.apply(o); //1