返回介绍

solution / 2700-2799 / 2754.Bind Function to Context / README_EN

发布于 2024-06-17 01:03:00 字数 2835 浏览 0 评论 0 收藏 0

2754. Bind Function to Context

中文文档

Description

Enhance all functions to have the bindPolyfill method. When bindPolyfill is called with a passed object obj, that object becomes the this context for the function.

For example, if you had the code:

function f() {
  console.log('My context is ' + this.ctx);
}
f();

The output would be "My context is undefined". However, if you bound the function:

function f() {
  console.log('My context is ' + this.ctx);
}
const boundFunc = f.boundPolyfill({ "ctx": "My Object" })
boundFunc();

The output should be "My context is My Object".

You may assume that a single non-null object will be passed to the bindPolyfill method.

Please solve it without the built-in Function.bind method.

 

Example 1:

Input: 
fn = function f(multiplier) { 
  return this.x * multiplier; 
}
obj = {"x": 10}
inputs = [5]
Output: 50
Explanation:
const boundFunc = f.bindPolyfill({"x": 10});
boundFunc(5); // 50
A multiplier of 5 is passed as a parameter.
The context is set to {"x": 10}.
Multiplying those two numbers yields 50.

Example 2:

Input: 
fn = function speak() { 
  return "My name is " + this.name; 
}
obj = {"name": "Kathy"}
inputs = []
Output: "My name is Kathy"
Explanation:
const boundFunc = f.bindPolyfill({"name": "Kathy"});
boundFunc(); // "My name is Kathy"

 

Constraints:

  • obj is a non-null object
  • 0 <= inputs.length <= 100

 

Can you solve it without using any built-in methods?

Solutions

Solution 1

type Fn = (...args) => any;

declare global {
  interface Function {
    bindPolyfill(obj: Record<any, any>): Fn;
  }
}

Function.prototype.bindPolyfill = function (obj) {
  return (...args) => {
    return this.call(obj, ...args);
  };
};

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

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

发布评论

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