JS实现call、apply、bind
- 实现call
Function.prototype.myCall = function(thisArg, ...args) {
const fn = Symbol('fn') // 声明一个独有的Symbol属性, 防止fn覆盖已有属性
thisArg = thisArg || window // 若没有传入this, 默认绑定window对象
thisArg[fn] = this // this指向调用call的对象,即我们要改变this指向的函数
const result = thisArg[fn](...args) // 执行当前函数
delete thisArg[fn] // 删除我们声明的fn属性
return result // 返回函数执行结果
}
//测试
foo.myCall(obj)
- 实现apply
Function.prototype.myApply = function(thisArg, args) {
const fn = Symbol('fn') // 声明一个独有的Symbol属性, 防止fn覆盖已有属性
thisArg = thisArg || window // 若没有传入this, 默认绑定window对象
thisArg[fn] = this // this指向调用call的对象,即我们要改变this指向的函数
const result = thisArg[fn](...args) // 执行当前函数
delete thisArg[fn] // 删除我们声明的fn属性
return result // 返回函数执行结果
}
//测试
foo.myApply(obj, [])
- 实现bind
Function.prototype.myBind = function (thisArg, ...args) {
var self = this
// new优先级
var fbound = function () {
self.apply(this instanceof self ? this : thisArg, args.concat(Array.prototype.slice.call(arguments)))
console.log(arguments)
}
// 继承原型上的属性和方法
fbound.prototype = Object.create(self.prototype);
return fbound;
}
//测试
const obj = { name: '写代码像蔡徐抻' }
function foo() {
console.log(this.name)
// console.log(arguments)
}
foo.myBind(obj, 'a', 'b', 'c')("x")
Function.prototype.bind=function(){
const args=Array.prototype.slice.call(arguments,0)
const obj=args.shift()
const that=this
return function(){
that.apply(obj,args.concat(Array.prototype.slice.call(arguments,0)))
}
}
function foo(a){
console.log(this)
console.log(a)
console.log(arguments)
}
const obj={
b:1
}
foo.bind(obj,10)(20)
附录:参考来源 手写实现call、bind、apply
参考来源手写bind的实现

浙公网安备 33010602011771号