call,apply,bind用法


title: call,apply,bind用法
date: 2018-05-28 23:00:00
tags: call apply bind
categories: 前端


call

var obj = {
   name: 'hht',
   age : 1
}

function f(name,age){
  this.name = name;
  this.age = age;
  console.log(this.name);
  console.log(this.age);
}

f.call(obj,'mmd',18);
image
  • call()方法調(diào)用一個函數(shù), 其具有一個指定的this值和分別地提供的參數(shù)(參數(shù)的列表).
  • call 的第一個參數(shù)是指定調(diào)用的這個函數(shù)的this ,非嚴格模式下this的值如果是null或者undefine ,那么這個this指向window
  • call 第二個以及之后的參數(shù)就是我們的arguments的值

apply

var obj = {
   name: 'hht',
   age : 1
}

function f(name,age){
  this.name = name;
  this.age = age;
  console.log(this.name);
  console.log(this.age);
}

f.apply(obj,['mmd',18]);
f.apply(obj,{0: 'mmd', 1: 18, length: 2});
image
  • call()方法的作用和 apply() 方法類似,只有一個區(qū)別,就是 call()方法接受的是若干個參數(shù)的列表,而apply()方法接受的是一個包含多個參數(shù)的數(shù)組, 或偽數(shù)組。

bind

var obj = {
   name: 'hht',
   age : 1
}

function f(){
  for(let i = 0; i < 4; i++)
  {
    console.log(arguments[i]);
  }
  console.log(this);
}

var f1Bind = f.bind(obj,'hht',18);
f1Bind();
f1Bind(1,2);
image
  • bind 綁定時接受的參數(shù)跟 call 一致.
  • bind 不會立即調(diào)用,它會生成一個新的函數(shù),你想什么時候調(diào)就什么時候調(diào)。
  • bind 綁定好的this不會改變
  • bind 綁定時的給的參數(shù)會成為這個綁定函數(shù)的固定參數(shù),調(diào)用這個函數(shù)時這幾個參數(shù)一定會在
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容