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实现 #106

Open
louzhedong opened this issue Dec 12, 2018 · 0 comments
Open

call和apply实现 #106

louzhedong opened this issue Dec 12, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

call() 方法使用一个指定的this值和若干个指定的参数来调用某个函数和方法

call调用例子


var apple = {
  size: 3
}

function eat() {
  console.log(this.size);
}

eat.call(apple); // 3

实现

Function.prototype.call2 = function (ctx) {
  var ctx = ctx || window;
  var args = [];
  for (var i = 1; i < arguments.length; i++) {
    args.push('arguments[' + i + ']');
  }
  ctx.fn = this;  // this为调用call的函数
  var result = eval('ctx.fn(' + args + ')');
  delete ctx.fn;
  return result;
}

apply 实现

Function.prototype.apply2 = function (ctx, array) {
  var ctx = ctx || window;
  ctx.fn = this;
  var result;
  if (!array) {
    result = ctx.fn();
  } else {
    var args = [];
    for (var i = 0; i < array.length; i++) {
      args.push('array[' + i + ']');
    }
    result = eval('ctx.fn(' + args + ')');
  }
  delete ctx.fn;
  return result
}
@louzhedong louzhedong changed the title bind和apply实现 call和apply实现 Dec 13, 2018
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