手写new, bind, call, apply
Willem Zhang Lv6

myNew

1
2
3
4
5
6
function myNew(constructor, ...args) {
let obj = {}
obj.__proto__ = constructor.Protorype
constructor.call(obj, ...args)
return obj
}

myBind

1
2
3
4
5
6
Function.prototype.myBind = function(obj=window, ...outerArgs){
let _this = this
return function(...innerArgs){
_this.call(obj, ...outerArgs.concat(innerArgs)) // call接收的是多个参数 apply接收的是数组
}
}

myCall

1
2
3
4
5
6
7
Function.prototype.myCall = function(obj=window, ...args){
obj.f = this
const res = obj.f(...args)
delete obj.f
return res
}

myApply

1
2
3
4
5
6
Function.prototype.myApply = function(obj=window, args){ // apply传入数组
obj.f = this
const res = obj.f(...args)
delete obj.f
return res
}

ref

【前端面试】new, bind, call, apply 手写

  • Post title:手写new, bind, call, apply
  • Post author:Willem Zhang
  • Create time:2022-03-22 22:36:25
  • Post link:https://ataraxia.top/2022/03/22/手写new-bind-call-apply/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments