apply、call 、bind做用和區別

apply、call 、bind有什麼做用?什麼區別?

JavaScript 的一大特色是,函數存在「定義時上下文」和「運行時上下文」以及「上下文是能夠改變的」這樣的概念。javascript

apply、call的做用

call和apply都是爲了改變某個函數運行時的上下文(context)而存在的,換句話說,就是爲了改變函數體內部this的指向。例如:vue

function fruits() {}

fruits.prototype = {
    color: "red",
    say: function () {
        console.log("My color is " + this.color);
    }
};

var apple = new fruits;
apple.say();    //My color is red
複製代碼

可是若是咱們有一個對象banana= {color : 'yellow'} ,咱們不想對它從新定義say方法,那麼咱們能夠經過使用call或apply方法:java

banana = {
    color: 'yellow'
};
apple.say.call(banana); //My color is yellow
apple.say.apply(banana); //My color is yellow
複製代碼

call、apply動態改變this執行上下文爲傳入的參數banana,使得banana具備了say()方法。react

當一個對象沒有某個方法,可是其餘對象的有,咱們能夠藉助call或apply用其它對象的方法來操做。git

apply、call的區別

apply、call做用徹底同樣,只是接受參數的方式不太同樣。例如:github

var func = function(arg1, arg2) {};
func.call(this, arg1, arg2);
func.apply(this, [arg1, arg2]);
複製代碼

其中 this 是你想指定的上下文。 call須要把參數按順序傳遞進去,而apply則是把參數放在數組裏再傳進去。數組

當函數參數是明確知道數量時建議用call 當函數參數數量不固定時建議用apply,而後把參數push進數組傳遞進去。app

經常使用方法:dom

  1. 數組之間追加
var array1 = [12 , "foo" , {name "Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
// array1值爲[12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100]
複製代碼
  1. 獲取數組中的最大值和最小值
var numbers = [5, 458 , 120 , -215 ];
var maxInNumbers = Math.max.apply(Math, numbers),   //458
    maxInNumbers = Math.max.call(Math,5, 458 , 120 , -215); //458
複製代碼
  1. 類數組使用數組方法
var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));
// 使getElementsByTagName()方法返回的類數組具備數組的方法
複製代碼

bind做用

bind()方法會建立一個新函數,稱爲綁定函數,當調用這個綁定函數時,綁定函數會以建立它時傳入bind()方法的第一個參數做爲this,傳入bind()方法的第二個以及之後的參數加上綁定函數運行時自己的參數按照順序做爲原函數的參數來調用原函數。函數

示例以下:

// 使用_this等保存this ,以便在改變了上下文以後繼續引用到它
var foo = {
  bar : 1,
  eventBind: function () {
    var _this = this;
    $('.someClass').on('click',function (event) {
      /* Act on the event */
      console.log(_this.bar);
    });
  }
}
// 使用bind()方法建立了一個新函數,當這個click事件綁定在被調用的時候,this指向調用bind()時傳入的第一個參數(即foo對象)。
var foo = {
  bar : 1,
  eventBind: function () {
    $('.someClass').on('click',function (event) {
      /* Act on the event */
      console.log(this.bar);
    }.bind(this));
  }
}
複製代碼

apply、call、bind比較

示例以下:

var obj = {
    x: 81,
};

var foo = {
    getX: function () {
      return this.x;
    }
}

console.log(foo.getX.bind(obj)());  //81
console.log(foo.getX.call(obj));    //81
console.log(foo.getX.apply(obj));   //81
複製代碼

三個輸出的都是81,可是注意看使用 bind() 方法的,他後面多了對括號。當你但願改變上下文環境以後並不是當即執行,而是回調執行的時候,使用 bind() 方法。而 apply/call 則會當即執行函數。

總結:

  • apply、call、bind三者都是用來改變函數的this的指向的;
  • apply、call、bind三者第一個參數都是this要指向的調用對象,也就是想指定的上下文;
  • apply、call、bind三者均可以利用後續參數傳參;
  • bind是返回對應函數,便於稍後調用;apply 、call則是當即調用。

下面代碼輸出什麼?爲何?

var john = {
  firstName: "John"
};
function func() {
  alert(this.firstName + ": hi!")
}
john.sayHi = func; // this指向當前執行上下文john
john.sayHi();
// 輸出:John: hi!
複製代碼

下面代碼輸出什麼?爲何?

func(); // this指向當前執行上下文window
function func() {
  alert(this);
}
// 輸出:window
複製代碼

下面代碼輸出什麼?爲何??

document.addEventListener('click', function(e){
    console.log(this); // this指向當前執行上下文document
    setTimeout(function(){
        console.log(this); // this指向當前執行上下文window
    }, 200);
}, false);
// 輸出:document window
複製代碼

下面代碼輸出什麼?爲何?

var john = {
  firstName: "John"
}

function func() {
  alert(this.firstName); // this指向當前執行上下文window
}
func.call(john); // call函數改變函數func()的執行上下文爲call()的第一個參數,即john,所以this指向執行上下文john
// 輸出:John
複製代碼

如下代碼有什麼問題?如何修改?

// 修改前
var module= {
  bind: function () {
    $btn.on('click', function () {
      console.log(this); //this指向當前執行上下文$btn
      this.showMsg(); // 當前執行上下文$btn沒有showMsg()方法,沒法調用
    });
  },

  showMsg: function () {
    console.log('餓了麼');
  }
};

// 修改後
var module= {
  bind: function () {
    const _this = this; //將this指向的當前執行上下文module保存爲_this
    $btn.on('click', function () {
      console.log(this); //this指向當前執行上下文$btn
      _this.showMsg(); // _this即module,能夠調用showMsg()方法
    });
  },

  showMsg: function () {
    console.log('餓了麼');
  }
};
複製代碼

另外最近正在寫一個編譯 Vue 代碼到 React 代碼的轉換器,歡迎你們查閱。

github.com/mcuking/vue…

相關文章
相關標籤/搜索