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 #9

Open
luichooy opened this issue Sep 3, 2019 · 0 comments
Open

自己实现call,apply,bind #9

luichooy opened this issue Sep 3, 2019 · 0 comments

Comments

@luichooy
Copy link
Owner

luichooy commented Sep 3, 2019

call

Function.prototype.myCall = function(context = window, ...args) {
  let fn = this;
  let key = Symbol("key");
  context[key] = fn;

  const res = context[key](...args);
  delete context[key];
  return res;
};

apply

Function.prototype.myApply = function(context = window, args) {
  let fn = this;
  let key = Symbol("key");
  context[key] = fn;

  const res = context[key](...args);
  delete context[key];
  return res;
};

bind

Function.prototype.myBind = function(context = window, ...args) {
  const fn = this;

  const bindFn = function() {
    return fn.apply(
      this instanceof bindFn ? this : context,
      args.concat(Array.prototype.slice.call(arguments))
    );
  };

  bindFn.prototype = Object.create(this.prototype);

  return bindFn;
};

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