true 调用 polyfil(没有扩展/剩余运算符);奖金:申请&绑定polyfill

发布于 2025-01-19 22:44:23 字数 1175 浏览 4 评论 0原文

我一直在练习呼叫,申请,绑定polyfills,并突然意识到,如果我使用传播/休息操作员,它并不是真正的多填充,无法弄清楚没有它的情况下如何通过呼叫中的参数,有什么想法吗?

//my attempt to write call polyfil without spread operator
//but it doesn't work
Function.prototype.call = function () {
  const obj = arguments[0];
  obj.fn = this;
  const args = Array(arguments).slice(1).reverse();
  while (args.length) {
    obj.fn.arguments.push(args.pop());
  }

  //obj.fn.arguments = Array(arguments).slice(1);
  obj.fn();
};

// that one works, but it uses spread operator
Function.prototype.call = function (obj, ...args) {
  obj.fn = this;
  obj.fn(...args);
};

Function.prototype.apply = function (obj, args) {
  obj.fn = this;
  obj.fn(...args);
};

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

  return function (...newArgs) {
    const allArgs = [...args, ...newArgs];
    fn.call(obj, ...allArgs);
    //fn.apply(obj, allArgs);
  };
};

let obj = {
  name: "Jack",
};

let myFunc = function (id, city) {
  console.log(`${this.name}, ${id}, ${city}`); 
};

let newFunc = myFunc.myBind(obj, "a_random_id");
newFunc("New York"); // Jack, a_random_id, New York

I've been practicing call, apply, bind polyfills and suddenly realized that it's not really a polyfill if I use spread/rest operators, can't figure out how to pass arguments in call without it, any ideas folks?

//my attempt to write call polyfil without spread operator
//but it doesn't work
Function.prototype.call = function () {
  const obj = arguments[0];
  obj.fn = this;
  const args = Array(arguments).slice(1).reverse();
  while (args.length) {
    obj.fn.arguments.push(args.pop());
  }

  //obj.fn.arguments = Array(arguments).slice(1);
  obj.fn();
};

// that one works, but it uses spread operator
Function.prototype.call = function (obj, ...args) {
  obj.fn = this;
  obj.fn(...args);
};

Function.prototype.apply = function (obj, args) {
  obj.fn = this;
  obj.fn(...args);
};

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

  return function (...newArgs) {
    const allArgs = [...args, ...newArgs];
    fn.call(obj, ...allArgs);
    //fn.apply(obj, allArgs);
  };
};

let obj = {
  name: "Jack",
};

let myFunc = function (id, city) {
  console.log(`${this.name}, ${id}, ${city}`); 
};

let newFunc = myFunc.myBind(obj, "a_random_id");
newFunc("New York"); // Jack, a_random_id, New York

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文