call,bind和apply都是Function上原型的方法,他們都是改變上下文this的指向。call和apply是馬上生效,而bind是調用生效。
在MDN中定義以下數組
call()方法去調用一個具備this值得方法和傳入一個數組參數app
語法函數
call(this.Arg,arg1,arg2) this.Arg:表示的是運行時的this,arg1,arg2傳入的參數this
用法prototype
// 找到數組的最大值 const arr=[2,1,3,4,5]; const max=Math.max.call(null,arr); console.log(max); //5 在這裏null表明的是window對象 // push 數組 const arr1=["a","s","d","f"]; const arr2=[1,2,3,4]; //擴大arr1的數組值 Array.prototype.concat.call(arr1,arr2); console.log(arr1)//[a,s,d,f,[1,2,3,4]]
const obj={ name:"llz", say:function(){ console.log(`你的名字是${this.name}`) } } obj.say.call(obj)//你的名字是llz const obj3={name:"玉萍"}; obj.say.call(obj3);//你的名字是玉萍 這種寫法能夠使obj3也能夠使用say方法,不須要在編寫重複代碼
const obj={name:"llz",age:18}; const info=function(name,age){ console.log(`you name:${name},you age ${age}`) }; info.call(obj,obj.name,obj.age)
var Person=function (obj){ this.obj=obj } Person.prototype.say=function(){ console.log(this.obj.name) } var Son=function(obj){ Person.call(this,obj) //用call將Person的上下文替換爲Son的 } Son.prototype=new Person() // 原型鏈繼承 var son1=new Son({name:"ii"}); son1.say()
// 用log方法重寫console.log 方法 // 用log方法打印多個參數 function log(){ console.log.apply(console,arguments) } log(1,2,3)
在MDN 中bind(),產生一個綁定函數,第一個參數是this,後面參數是綁定函數在運行時綁定的this,下面來個小例子code
// 通常狀況,咱們將對象中的方法拿出來,而保證這個方法的this綁定不變 const obj1={name:"llz"} const obj={ getNum:function(){ console.log(this.name); } } const nameFnc=obj.getNum.bind(obj1); nameFnc()
1.apply 、 call 、bind 三者都是用來改變函數的this指向 2.call和apply是馬上生效,而bind是調用生效對象