標籤:color javascrip nbsp call 調用 對象 直接 返回 原型
總結一句話:javascript函數裡的this,始終指向調用該函數的直接對象。當然通過apply(),call(),bind()這幾個方法可以更改this除外
執行個體1:alert(this === window); //true 調用該函數的直接對象是全域window
執行個體2:var test = function() { alert(this === window)}; test(); //true 調用該函數的直接對象仍是全域window
執行個體3:var test = function() { alert(this === window)}; new test(); //false 因為new關鍵字建立了一個Null 物件,相當於由這個Null 物件作為建構函式調用的直接對象,此時this就不是指向window而是指向Null 物件,並將Null 物件進行初始化作為傳回值。
執行個體4:var test = { ‘a‘: 1, ‘b‘: function(){ alert(this === test);}}; test.b() //true 這是test作為函數test.b調用的直接對象
執行個體5: var test = {‘a‘: 1, ‘b‘: {‘b1‘: function(){ alert(this === test.b); }}}; test.b.b1(); //true 這時test.b作為函數test.b.b1調用的直接對象
執行個體6: var test = function(){ var inner = function(){ alert(this === window);} inner(); }; test(); //true 類似閉包函數裡的this,無論多少層,調用函數的直接對象始終為全域window
執行個體7: 關於原型鏈繼承 var test = function(){}; var test2 = function(){ this.a = function(){ alert(this === p1);}}; var p2 = new test2(); test.prototype = p2; test.prototype.constructor = test;var p1 = new test(); p1.a(); //true 此時p1作為函數p2.a調用的直接對象
執行個體8:dom節時間點事件監聽函數的this <div onclick="shw(this)"></div> 此時的this指向節點元素對象
javascript之this