1. 程式人生 > >this指向及改變this指向

this指向及改變this指向

1.全域性下的this指向window

this.a=1;
alert(window.a); //1

2.事件裡面的this指向事件源

var obj=document.getElementById('oDiv');
obj.onclick=function(){   
  alert(this.innerHTML) ;//這裡的this指向obj
}

3.函式中的this誰呼叫就指向誰

var o={
  name:'liuhua',
  test:function(){
  alert(this.name)
  }
}
o.test();  //liuhua,這裡函式由o呼叫,指向O
//注意:
var ff=o.test;
ff();  //此時this指向ff

call與apply改變this指向

call()

function.call(obj[,arg1[, arg2[, [,.argN]]]]])

呼叫call的物件必須是個函式function

call的第一個引數將會是function改變上下文後指向的物件(想要this指向誰)

第二個引數開始可以接收任意個引數,這些引數將會作為function的引數傳入function

apply()

function.apply(obj[,argArray])

call方法的使用基本一致,但是隻接收兩個引數,其中第二個引數必須是一個陣列或者類陣列

var o={
    name:'cj',
    print:function(){
        alert(this.name);
       }
   }
 function log(a,b){
     alert(this[a]); 
     alert(this[b]);
   };
//本來指向window,通過call,apply方法指向了O物件,所以才能讀取到name,全域性下是沒有name的
log.call(o,'name','age');   //cj    undefined
log.apply(o,['name','age']);   //cj   undefined