美文网首页
[Do it youself]bind, call, apply

[Do it youself]bind, call, apply

作者: 小丸子啦啦啦呀 | 来源:发表于2022-03-02 18:20 被阅读0次

    bind

    // Test case
    function show(){
      console.log(this.name, this.age);
      console.log(arguments[0]);
    }
    
    show.myBind({ name: "coco", age: 18 }, 'female')(); // should show coco, 18 female
    
    Function.prototype.myBind = function(context){
      const _this = this;
      const args = Array(...arguments).slice(1);
      return function(){
        return _this.apply(context,  [...arguments, ...args])
      }
    }
    

    call

    // Test case
    function show(gender){
      console.log(this.name, this.age, gender);
    }
    
    show.myCall({ name: "coco", age: 18 }, 'female'); // should show coco, 18,  female
    
    Function.prototype.myCall = function(){
       const [context, ...args] = Array(...argument);
    
       const result = context.fn(...args);
       delete context.fn;
       return result;
    }
    

    apply

    // Test case
    function show(gender){
      console.log(this.name, this.age, gender);
    }
    
    show.myApply({ name: "coco", age: 18 }, 'female'); // should show coco, 18,  female
    
    Function.prototype.myApply = function(){
       const [context, args] = Array(...argument);
    
       const result = context.fn(...args);
       delete context.fn;
       return result;
    }
    

    new

    // Test case
    function Person(name){
      this.name = name
    }
    
    const person = myNew(Person, "coco")
    console.log(person.name);
    console.log(person.__proto__ === Person.prototype)
    
    function muNew(constructer){
      let obj = {};
      const args = Array(arguments).slice(1);
      constructer.apply(obj, args);
      obj.__proto__ = constructer.prototype;
      return obj;
    }
    

    相关文章

      网友评论

          本文标题:[Do it youself]bind, call, apply

          本文链接:https://www.haomeiwen.com/subject/ppddrrtx.html