-
不传入第一个参,则上下文默认window
-
改变this的指向,让新的对象能执行该函数并能接受参数
Function.prototype.myCall = function(context){ if (typeof this !== 'function'){ throw new TypeError('Error') } // context为可选参数,不传默认上下文为window context = context || window // 给context创建一个fn属性,并将值设置为需要调用的函数 context.fn = this // 因为call可以传入多个参数作为调用函数的参数,所以需要将参数剥离出来 const args = [...arguments].slice(1) // 调用函数 const result = context.fn(...args) // 并将对象上的函数删除 delete context.fn return result }
// 实现与call类数,区别在于对参数的处理 Function.prototype.myApply = function(context){ if (typeof this !== 'function'){ throw new TypeError('Error') } // context为可选参数,不传默认上下文为window context = context || window // 给context创建一个fn属性,并将值设置为需要调用的函数 context.fn = this let result if (arguments[1]){ result = context.fn(...arguments[1]) }else{ result = context.fn() } // 并将对象上的函数删除 delete context.fn return result }
Function.prototype.myBind = function(context){ if (typeof this !== 'function'){ throw new TypeError('Error') } const _this = this const args = [...arguments].slice(1) // 返回一个函数 return function F(){ // 因为返回了一个函数,我们可以new F(), 所以需要判断 if (this instanceof F){ return new _this(...args, ...arguments) } return _this.apply(context, args.concat(...arguments)) } }
// 传入一个thisArgs和参数列表,thisArgs指定调用者,也就是this对象 // thisArgs不传、传null或者undefined,this指向window // 传另一个函数的函数名,this指向这个函数的引用 // 传字符串、数值等buer类型的基础数据类型,this指向其包装对象 // 传递对象,则指向对象 fun.call(thisArg[,arg1[, arg2[, ...]]])
apply
与call
的区别在于传递参数方式不同,apply
必须传递一个数组,而call
运行传入参数列表bind
传参与call
类似,其解决了call
和apply
都会自动执行对应函数的情况,即bind
在实现改变函数this
的同时又不会自动执行目标函数
JS call、apply、bind 函数
最新推荐文章于 2022-12-05 00:14:42 发布