类似之处:数组
fn.call(thisObj, arg1, arg2 ...)
fn.apply(thisObj, [arg1, arg2 ...])
const newFn = fn.bind(thisObj); newFn(arg1, arg2...)
call
语法浏览器
fun.call(thisArg, arg1, arg2, ...)
thisArg
: 在fun函数运行时指定的this值。须要注意的是,指定的this值并不必定是该函数执行时真正的this值,若是这个函数处于非严格模式下,则指定为null和undefined的this值会自动指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的this会指向该原始值的自动包装对象。arg1, arg2, ...
指定的参数列表apply
语法fun.apply(thisArg, [argsArray])
thisArg
在 fun 函数运行时指定的 this 值。须要注意的是,指定的 this 值并不必定是该函数执行时真正的 this 值,若是这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的 this 会指向该原始值的自动包装对象。argsArray
一个数组或者类数组对象,其中的数组元素将做为单独的参数传给 fun 函数。若是该参数的值为null 或 undefined,则表示不须要传入任何参数。从ECMAScript 5 开始能够使用类数组对象。bind
语法fun.bind(thisArg[, arg1[, arg2[, ...]]])
thisArg
当绑定函数被调用时,该参数会做为原函数运行时的 this 指向。当使用new 操做符调用绑定函数时,该参数无效。arg1, arg2, ...
当绑定函数被调用时,这些参数将置于实参以前传递给被绑定的方法。// 有只猫叫小黑,小黑会吃鱼 const cat = { name: '小黑', eatFish(...args) { console.log('this指向=>', this); console.log('...args', args); console.log(this.name + '吃鱼'); }, } // 有只狗叫大毛,大毛会吃骨头 const dog = { name: '大毛', eatBone(...args) { console.log('this指向=>', this); console.log('...args', args); console.log(this.name + '吃骨头'); }, } console.log('=================== call ========================='); // 有一天大毛想吃鱼了,但是它不知道怎么吃。怎么办?小黑说我吃的时候喂你吃 cat.eatFish.call(dog, '汪汪汪', 'call') // 大毛为了表示感谢,决定下次吃骨头的时候也喂小黑吃 dog.eatBone.call(cat, '喵喵喵', 'call') console.log('=================== apply ========================='); cat.eatFish.apply(dog, ['汪汪汪', 'apply']) dog.eatBone.apply(cat, ['喵喵喵', 'apply']) console.log('=================== bind ========================='); // 有一天他们以为每次吃的时候再喂太麻烦了。干脆直接教对方怎么吃 const test1 = cat.eatFish.bind(dog, '汪汪汪', 'bind') const test2 = dog.eatBone.bind(cat, '喵喵喵', 'bind') test1() test2()
this
指向的时候才会用到call
`apply`bind
fn.call(thisObj, arg1, arg2 ...)
fn.apply(thisObj, [arg1, arg2 ...])
const newFn = fn.bind(thisObj); newFn(arg1, arg2...)