call apply bind 使用
call apply bind , 均是用于改变函数调用时 this 指向,第一个参数都是 this 指向的对象, call 、 apply 调用就立即执行函数, call 第二参数开始是具体参数,apply 第二参数数组, bind 调用时可以传参并且返回一个函数,返回的函数调用时也可以传参。
fun.call(thisArg, param1, param2, ...)fun.apply(thisArg, [param1, param2, ...])fun.bind(thisArg, param1, param2, ...)const obj = {a: '1'}function zz(a, b) {console.log(this, a, b);}zz.apply(obj, [1, 2]) //{a: '1'} 1 2zz.call(obj, 1, 2) //{a: '1'} 1 2zz.bind(obj, 1, 2)() //{a: '1'} 1 2
apply 实现
利用改变 this 指向的特性
function zz(a, b) {console.log(this, a, b);}let obj = {a: '1'}Function.prototype.myapply = function(context) {context = context || windowlet args = [...arguments].slice(1)[0] || [];context.originFn = this;const result = context.originFn(...args)delete context.originFn;return result;}zz.myapply(obj, [1, 3]) //{ a: '1'} 1 3
call 实现
Function.prototype.mycall = function(context) {context = context || windowconst args = [...arguments].slice(1);const that = this;return that.myapply(context, args)}zz.mycall(obj, 1, 5) ////{ a: '1'} 1 5
bind 实现
Function.prototype.mybind = function(context) {if (typeof this !== 'function') {throw new TypeError('Error');}const that = this;const args = [...arguments].slice(1);return function newFn() {if (this instanceof newFn) {return new that(...args, ...arguments);}return that.myapply(context, args.concat(...arguments));}}let yy = zz.mybind(obj)yy(1, 2) // { a: '1'} 1 2
