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

5.模拟call、apply的实现 #6

Open
conan1992 opened this issue Dec 2, 2019 · 0 comments
Open

5.模拟call、apply的实现 #6

conan1992 opened this issue Dec 2, 2019 · 0 comments

Comments

@conan1992
Copy link
Owner

1、模拟call的实现

Function.prototype.call2 = function(context){
  let args = [];
  context= context? Object(context) : window;
  for(let i=1;i<arguments.length;i++){
    args.push('arguments['+i+']')
  }
  context.fn = this;
  let result = eval('context.fn('+args+')');//因为'context.fn(' + args +')'本质上是字符串拼接,会自动调用toString()方法
  delete context.fn
  return result
}

2、模拟apply的实现

Function.prototype.apply2 = function(context, arr){
  let args = [];
  context= context? Object(context) : window;
  context.fn = this;
  let result;
  if(arr){
    for(let i=0;i<arr.length;i++){
      args.push('arr['+i+']')
    }
    result = eval('context.fn('+args+')');//因为'context.fn(' + args +')'本质上是字符串拼接,会自动调用toString()方法\
  }else{
    result = context.fn();
  }
  delete context.fn
  return result
}

参考自木易杨大佬的文章

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant