手写js的apply、call、bind

面试中部分公司要求手写applay、call、bind,这里我就针对apply、call、bind自己写一个。

自定义apply

Function.prototype.myApply = function (context, args) {
   const key = Symbol('key')
   context = context || window
   context[key] = this
   const result = context[key](...args)
   delete context[key]
   return result
}

let a = {
       name: 'jack',
       getName: function (msg) {
          return msg + this.name;
       }
}

console.log("myApply", a.getName.myApply({ name: '张三' }, ['hello']))

自定义call

Function.prototype.myCall = function (context, ...args) {
        const key = Symbol('key')
        context = context || window
        context[key] = this
        const result = context[key](...args)
        delete context[key]
        return result
}

let a = {
       name: 'jack',
       getName: function (msg) {
          return msg + this.name;
       }
}

console.log("myApply", a.getName.myApply({ name: '张三' }, ['hello']))

自定义bind

Function.prototype.myBind = function (context, ...args) {
           if (typeof this !== "function") {
               throw new Error("this must be a function");
          }
          var self = this;
          var fbound = function () {
          return  self.apply(this instanceof self ? this : context, args.concat(Array.prototype.slice.call(arguments)));
       }
      if (this.prototype) {
          fbound.prototype = Object.create(this.prototype);
      }
      return fbound;
}
const name = a.getName.bind({ name: '张三' }, 'hello')
console.log(name())

和js中的apply、call、bind的功能完全一样。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值