Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

模拟实现一个call、apply、bind方法 #21

Open
LiuL0703 opened this issue Dec 25, 2018 · 0 comments
Open

模拟实现一个call、apply、bind方法 #21

LiuL0703 opened this issue Dec 25, 2018 · 0 comments

Comments

@LiuL0703
Copy link
Owner

LiuL0703 commented Dec 25, 2018

模拟实现bind方法

if(!Function.prototype.bind){
  Function.prototype.bind = function(oThis){
    if(typeof this !== 'function'){
      throw new TypeError();
    }
    var aArgs = [].slice.call(arguments,1),
        self = this,
        fNOP = function(){},
        fBound  = function() {
          return self.apply(this instanceof fNOP
                 ? this
                 : oThis,
                 aArgs.concat([].slice.call(arguments)));
        };
    if(this.prototype){
      fNOP.prototype = this.prototype;
    }
    fBound = new fNOP();
    return fBound;
  };
}

模拟实现一个call与apply方法

思路

  • 将函数设为对象属性
  • 执行该函数
  • 删除该函数

call

Function.prototype.call = function(context){
  var context = cotext || window;
  context.fn = this;
  var args = [];
  for(var i = 1; i < arguments.length; i++){
    args.push('arguments['+i+']');
  }
  var result = eval('context.fn('+args+')');
  delete context.fn;
  return result;
} 

apply

Function.prototype.apply = function(context, arr){
  var context = context || window;
  contex.fn = this;
  var reslut = [];
  if(!arr){
    result = context.fn(arr);
  }else{
    var args = [];
    for(var i = 0; i < arr.length; i++){
      args.push('arguments['+i+']');
    }
    result = eval('context.fn('+arr')');
  }
  delete context.fn;
  return result;
}

三者区别

  • call和apply的区别是传入的参数不同,
  • apply 方法传入两个参数:一个是作为函数上下文的对象,另外一个是作为函数参数所组成的数组
  • call 方法第一个参数也是作为函数上下文的对象,但是后面传入的是一个参数列表,而不是单个数组。
    call和apply与 bind 最大的区别是 call apply调用即执行了所对应的方法,bind的返回值是改变指向后的这个函数(未执行)
@LiuL0703 LiuL0703 changed the title 自己实现一个bind 自己实现一个bind方法 Dec 25, 2018
@LiuL0703 LiuL0703 changed the title 自己实现一个bind方法 模拟实现一个call、apply、bind方法 Mar 25, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant