call、appy、bindを手動で実現

17925 ワード

call、appy、bindを手動で実現
コールを実現する
//      
Function.prototype.myCall = function (context, ...args) {
     
  context = context || window;
  console.log("myCall", context);
  context._fn_ = this;// fn               ,          context        
  let result = context._fn_(...args);
  delete context.fn;
  return result;
}

//      
Function.prototype.myCall2 = function (context) {
     
  context = context || window;// context null    window
  let fn = Symbol();
  let args = [...arguments].slice(1);//    context       
  context[fn] = this;//    fn       
  let result = context[fn](...args);
  delete context[fn];
  return result;
}
//   
let Person_Call = {
     
  name: "Tom",
  say: function (...args) {
     
    console.log(this)
    console.log(`  ${
       this.name},   ${
       args[0]},     ${
       args[1]}`)
  }
}
let person1 = {
     
  name: "Jack"
}

Person_Call.say.myCall(person1, 19, "  ");//   Jack,   19,       
コールを実現する
//   apply
Function.prototype.myApply = function (context) {
     
  context = context || window;// context null    window
  let fn = Symbol();
  let args = [...arguments].slice(1);//    context       
  context[fn] = this;//    fn       
  let result = context[fn](args); //       ,    call  
  delete context[fn];
  return result;
}

//        say       args  ...args
let Person_Apply = {
     
  name: "Tom",
  say: function (args) {
     
    console.log(this)
    console.log(`  ${
       this.name},   ${
       args[0]},     ${
       args[1]}`)
  }
}
let person1 = {
     
  name: "Jack"
}
//       
Person_Apply.say.myApply(person1, [19, "  "])//   Jack,   19,       
ビッドを実現
//   bind 
Function.prototype.myBind = function (context) {
     
  //      this   ,        this
  let self = this
  //          ,    (        myBind        )
  let arg = [...arguments].slice(1)
  //       
  return function () {
     
    //                         (        myBind           )
    let newArg = [...arguments]
    console.log(newArg)
    //       this,         
    //            return
    return self.apply(context, arg.concat(newArg));
}
//     
let Person_Bind = {
     
  name: "Tom",
  say: function (...args) {
     
    console.log(this)
    console.log(`  ${
       this.name},   ${
       args[0]},     ${
       args[1]}`)
  }
}
let person1 = {
     
  name: "Jack"
} 
//  call                
var per = Person_Bind.say.myBind(person1, 20, "  ");
per();//   Jack,   20,