JS中call,apply的區別及其用法

共同點

  • 能夠改變函數的this指向   

    call和apply的第一個參數爲this的指向,傳null時,this指向window   javascript

var obj = {name: 'lisi'}
function fn() {
   console.log(this)  
}
fn.call(null)    //this指向window
fn.apply(null)   //this指向window
fn.call(obj)     //this指向obj
fn.apply(obj)    //this指向obj

不一樣點  

  • call傳參形式是,從第二個開始一個一個傳

  • apply的第二個參數爲數組,數組的每一項爲函數的參數

fn.call(null,1,2,3)   
fn.apply(null,[1,2,3])   

應用

  • 僞數組變爲真數組  [].slice.call(eles);  
相關文章
相關標籤/搜索