標籤:構造 2.3 class blog call val ima cal size
1.首先要明確: 誰最終調用函數,this指向誰 this指向的永遠只可能是對象!!!!! this指向誰永遠不取決於this寫在哪,而取決於函數在哪裡調用! this指向的對象,我們稱之為函數的上下文context,也叫做函數的調用者是誰! 2.this指向的規律(與函數調用的方式息息相關) this指向的情況取決於函數調用的方式有哪些(總結如下): 2.1.通過函數名()直接調用--this 指向window;
function func(){ console.log(this); }
func();
2.2.通過對象.函數名()調用的--this指向這個對象
狹義對象: this指向--obj
var obj={ name:"obj", func1:func }; obj.func1();
廣義對象: this指向--div
document.getElementById("div").onclick=function(){ this.style.backgroundColor="red"; }
2.3. this指向——數組arr
var arr=[func,1,2,3]; arr[0]();
2.4.函數作為window內建函數的回呼函數調用,this指向window setInterval,setTimout等
setInterval(func,1000); setTimeout(func,1000)
2.5.函數作為建構函式,用new關鍵字調用時:this指向新定義的對象obj var obj=new func();
2.6. 通過call、apply、bind調用,this指向我們規定的對象。
Func.call(obj,參數一,參數2,參數3.。。。)
Func.allply(obj,[ 參數一,參數2,參數3.。。。])
Func.bind(obj)( 參數一,參數2,參數3) var f = func.bind(obj). f(…….);
小試牛刀:
var fullname = ‘John Doe‘; var obj = { fullname: ‘Colin Ihrig‘, prop: { fullname: ‘Aurelio De Rosa‘, getFullname: function() { return this.fullname; } } }; console.log(obj.prop.getFullname()); // Aurelio De Rosa //函數最終調用者:obj.prop this--->obj.prop var test = obj.prop.getFullname; console.log(test()); // John Doe // 函數最終調用者: 函數() window this-->window
JS中精選this關鍵字的指向規律你記住了嗎