1、在一般函數中使用 this 指全局對象 window
function fn(){
this.x = 1 } fn(); //相當於window.fn()
2、作為對象方法使用 this 指該對象
function fn(){
alert(this.x) //this是調用該函數的obj對象 輸出test
} var obj = {'fn':fn,'x':'test'} obj.fn();
3、作為構造函數使用 this 指new 函數出的對象
function fn(){
this.x = 123; //this是調用該函數的obj對象
} var obj = new fn(); //obj = {x:123}
4、apply 調用函數,apply 方法作用是改變函數的調用對象,此方法第一個參數為改變后的調用函數的對象,函數里this指第一個參數
var x = 11;
function fn(){ alert(this.x) } var obj = {'fn':fn,'x':22} var obj2 = {'x':33} obj.fn.apply(); // 11 ,apply()參數為空時,默認調用的是全局對象,this當前指全局對象 obj.fn.apply(obj); // 22 obj.fn.apply(obj2); // 33