{ "data": { "question": { "questionId": "2790", "questionFrontendId": "2693", "categoryTitle": "JavaScript", "boundTopicId": 2275502, "title": "Call Function with Custom Context", "titleSlug": "call-function-with-custom-context", "content": "

Enhance all functions to have the callPolyfill method. The method accepts an object obj as it's first parameter and any number of additional arguments. The obj becomes the this context for the function. The additional arguments are passed to the function (that the callPolyfill method belongs on).

\n\n

For example if you had the function:

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

Calling this function like tax(10, 0.1) will log "The cost of undefined is 11". This is because the this context was not defined.

\n\n

However, calling the function like tax.callPolyfill({item: "salad"}, 10, 0.1) will log "The cost of salad is 11". The this context was appropriately set, and the function logged an appropriate output.

\n\n

Please solve this without using the built-in Function.call method.

\n\n

 

\n

Example 1:

\n\n
\nInput:\nfn = function add(b) {\n  return this.a + b;\n}\nargs = [{"a": 5}, 7]\nOutput: 12\nExplanation:\nfn.callPolyfill({"a": 5}, 7); // 12\ncallPolyfill sets the "this" context to {"a": 5}. 7 is passed as an argument.\n
\n\n

Example 2:

\n\n
\nInput: \nfn = function tax(price, taxRate) { \n return `The cost of the ${this.item} is ${price * taxRate}`; \n}\nargs = [{"item": "burger"}, 10, 1,1]\nOutput: "The cost of the burger is 11"\nExplanation: callPolyfill sets the "this" context to {"item": "burger"}. 10 and 1.1 are passed as additional arguments.\n
\n\n

 

\n

Constraints:

\n\n\n", "translatedTitle": "使用自定义上下文调用函数", "translatedContent": "

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

\n\n

例如,如果有以下函数:

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

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

\n\n

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

\n\n

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

\n\n

 

\n\n

示例 1:

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

示例 2:

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

 

\n\n

提示:

\n\n\n", "isPaidOnly": false, "difficulty": "Medium", "likes": 1, "dislikes": 0, "isLiked": null, "similarQuestions": "[]", "contributors": [], "langToValidPlayground": "{\"cpp\": true, \"java\": true, \"python\": true, \"python3\": true, \"mysql\": false, \"mssql\": false, \"oraclesql\": false, \"c\": false, \"csharp\": false, \"javascript\": false, \"ruby\": false, \"bash\": false, \"swift\": false, \"golang\": false, \"scala\": false, \"html\": false, \"pythonml\": false, \"kotlin\": false, \"rust\": false, \"php\": false, \"typescript\": false, \"racket\": false, \"erlang\": false, \"elixir\": false, \"dart\": false}", "topicTags": [], "companyTagStats": null, "codeSnippets": [ { "lang": "JavaScript", "langSlug": "javascript", "code": "/**\n * @param {Object} context\n * @param {any[]} args\n * @return {any}\n */\nFunction.prototype.callPolyfill = function(context, ...args) {\n\n}\n\n/**\n * function increment() { this.count++; return this.count; }\n * increment.callPolyfill({count: 1}); // 2\n */", "__typename": "CodeSnippetNode" }, { "lang": "TypeScript", "langSlug": "typescript", "code": "declare global { \n interface Function {\n callPolyfill(context: Record, ...args: any[]): any;\n\t}\n}\n\nFunction.prototype.callPolyfill = function(context, ...args): any {\n\n}\n\n/**\n * function increment() { this.count++; return this.count; }\n * increment.callPolyfill({count: 1}); // 2\n */", "__typename": "CodeSnippetNode" } ], "stats": "{\"totalAccepted\": \"397\", \"totalSubmission\": \"510\", \"totalAcceptedRaw\": 397, \"totalSubmissionRaw\": 510, \"acRate\": \"77.8%\"}", "hints": [], "solution": null, "status": null, "sampleTestCase": "function add(b) { return this.a + b; }\n[{\"a\":5},7]", "metaData": "{\n \"name\": \"callPolyfill\",\n \"params\": [\n {\n \"type\": \"string\",\n \"name\": \"context\"\n },\n {\n \"type\": \"string\",\n \"name\": \"args\"\n }\n ],\n \"return\": {\n \"type\": \"string\"\n },\n \"languages\": [\n \"javascript\",\n \"typescript\"\n ],\n \"manual\": true\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "envInfo": "{\"javascript\":[\"JavaScript\",\"

\\u7248\\u672c\\uff1aNode.js 16.13.2<\\/code><\\/p>\\r\\n\\r\\n

\\u60a8\\u7684\\u4ee3\\u7801\\u5728\\u6267\\u884c\\u65f6\\u5c06\\u5e26\\u4e0a --harmony<\\/code> \\u6807\\u8bb0\\u6765\\u5f00\\u542f \\u65b0\\u7248ES6\\u7279\\u6027<\\/a>\\u3002<\\/p>\\r\\n\\r\\n

lodash.js<\\/a> \\u5e93\\u5df2\\u7ecf\\u9ed8\\u8ba4\\u88ab\\u5305\\u542b\\u3002<\\/p>\\r\\n\\r\\n

\\u5982\\u9700\\u4f7f\\u7528\\u961f\\u5217\\/\\u4f18\\u5148\\u961f\\u5217\\uff0c\\u60a8\\u53ef\\u4f7f\\u7528 datastructures-js\\/priority-queue@5.3.0<\\/a> \\u548c datastructures-js\\/queue@4.2.1<\\/a>\\u3002<\\/p>\"],\"typescript\":[\"TypeScript\",\"

TypeScript 4.5.4<\\/p>\\r\\n\\r\\n

Compile Options: --alwaysStrict --strictBindCallApply --strictFunctionTypes --target ES2020<\\/p>\\r\\n\\r\\n

lodash.js<\\/a> \\u5e93\\u5df2\\u7ecf\\u9ed8\\u8ba4\\u88ab\\u5305\\u542b\\u3002<\\/p>\\r\\n\\r\\n

\\u5982\\u9700\\u4f7f\\u7528\\u961f\\u5217\\/\\u4f18\\u5148\\u961f\\u5217\\uff0c\\u60a8\\u53ef\\u4f7f\\u7528 datastructures-js\\/priority-queue@5.3.0<\\/a> \\u548c datastructures-js\\/queue@4.2.1<\\/a>\\u3002<\\/p>\"]}", "book": null, "isSubscribed": false, "isDailyQuestion": false, "dailyRecordStatus": null, "editorType": "CKEDITOR", "ugcQuestionId": null, "style": "LEETCODE", "exampleTestcases": "function add(b) { return this.a + b; }\n[{\"a\":5},7]\nfunction tax(price, taxRate) { return `The cost of the ${this.item} is ${price * taxRate}`; }\n[{\"item\":\"burger\"},10,1.1]", "__typename": "QuestionNode" } } }