用call实现bind方法以及new的实现

 ES5的写法 封装mybind 通过函数原型添加属性
Function.prototype.myBind = function (obj, ...args1) { // this 是原本的函数 // console.log(this) let self = this return function (...args2) { // console.log(this) // console.log(self) return self.call(obj, ...args1,...args2) } }
  ES6  
Function.prototype.myBind = function(obj, ...args1){ return (...args2) => (this.call(obj,...args1,...args2)) }

bind可实现参数的分批传入

let f={age:18}
function foo(a,b,c){
     this.a =  a;
     this.b = b;
     this.c = c          
}
let result=foo.bind(f,1)
result(2,3)
function myNew(Foo, ...arg){
  //   let result = {}
  //   result.__proto__ = Foo.prototype // 对 result的原型进行修改,指向正确对的对象
  //   Foo.apply(result, arg)
  //   return result
  // }

 

posted @ 2020-08-23 23:04  小码LQ~  阅读(184)  评论(0)    收藏  举报