LeetCode 题解工作台

使用自定义上下文调用函数

增强所有函数,使其具有 callPolyfill 方法。该方法接受一个对象 obj 作为第一个参数,以及任意数量的附加参数。 obj 成为函数的 this 上下文。附加参数将传递给该函数(即 callPolyfill 方法所属的函数)。 例如,如果有以下函数: function tax(price,…

category

0

题型

code_blocks

1

代码语言

hub

0

相关题

当前训练重点

中等 · call·function·custom·context·core·interview·pattern

bolt

答案摘要

declare global { interface Function {

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 call·function·custom·context·core·interview·pattern 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

增强所有函数,使其具有 callPolyfill 方法。该方法接受一个对象 obj 作为第一个参数,以及任意数量的附加参数。obj 成为函数的 this 上下文。附加参数将传递给该函数(即 callPolyfill 方法所属的函数)。

例如,如果有以下函数:

function tax(price, taxRate) {
  const totalCost = price * (1 + taxRate);
  console.log(`The cost of ${this.item} is ${totalCost}`);
}

调用 tax(10, 0.1) 将输出 "The cost of undefined is 11" 。这是因为 this 上下文未定义。

然而,调用 tax.callPolyfill({item: "salad"}, 10, 0.1) 将输出 "The cost of salad is 11" 。this 上下文被正确设置,函数输出了适当的结果。

请在不使用内置的 Function.call 方法的情况下解决这个问题。

 

示例 1:

输入:
fn = function add(b) {
  return this.a + b;
}
args = [{"a": 5}, 7]
输出:12
解释:
fn.callPolyfill({"a": 5}, 7); // 12
callPolyfill 将 "this" 上下文设置为 {"a": 5} ,并将 7 作为参数传递。

示例 2:

输入:
fn = function tax(price, taxRate) { 
 return `The cost of the ${this.item} is ${price * taxRate}`; 
}
args = [{"item": "burger"}, 10, 1,1]
输出:"The cost of the burger is 11"
解释:callPolyfill 将 "this" 上下文设置为 {"item": "burger"} ,并将 10 和 1.1 作为附加参数传递。

 

提示:

  • typeof args[0] == 'object' and args[0] != null
  • 1 <= args.length <= 100
  • 2 <= JSON.stringify(args[0]).length <= 105
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
declare global {
    interface Function {
        callPolyfill(context: Record<any, any>, ...args: any[]): any;
    }
}

Function.prototype.callPolyfill = function (context, ...args): any {
    const fn = this.bind(context);
    return fn(...args);
};

/**
 * function increment() { this.count++; return this.count; }
 * increment.callPolyfill({count: 1}); // 2
 */
speed

复杂度分析

指标
时间complexity is O(n) where n is the number of arguments because they are iterated when applying to the function. Space complexity is O(1) extra, aside from the temporary property created on obj.
空间**
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect candidates to handle dynamic this binding and argument application.

  • question_mark

    Look for proper cleanup of temporary properties to avoid side effects.

  • question_mark

    Watch for understanding of function context and how JavaScript call/apply patterns work.

warning

常见陷阱

外企场景
  • error

    Failing to use the first argument as this context correctly.

  • error

    Not passing remaining arguments in the proper order, causing incorrect results.

  • error

    Leaving temporary properties on obj, which may modify the object unexpectedly.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Implement applyPolyfill to accept an array of arguments instead of individual arguments.

  • arrow_right_alt

    Support functions that return values versus just logging output.

  • arrow_right_alt

    Handle primitive types for this by wrapping them in their object equivalents.

help

常见问题

外企场景

使用自定义上下文调用函数题解:call·function·custom·co… | LeetCode #2693 中等