mirror of
				https://gitee.com/coder-xiaomo/leetcode-problemset
				synced 2025-11-04 11:43:12 +08:00 
			
		
		
		
	
		
			
				
	
	
		
			55 lines
		
	
	
		
			2.2 KiB
		
	
	
	
		
			HTML
		
	
	
	
	
	
			
		
		
	
	
			55 lines
		
	
	
		
			2.2 KiB
		
	
	
	
		
			HTML
		
	
	
	
	
	
<p>增强所有函数,使其具有 <code>callPolyfill</code> 方法。该方法接受一个对象 <code>obj</code> 作为第一个参数,以及任意数量的附加参数。<code>obj</code> 成为函数的 <code>this</code> 上下文。附加参数将传递给该函数(即 <code>callPolyfill</code> 方法所属的函数)。</p>
 | 
						||
 | 
						||
<p>例如,如果有以下函数:</p>
 | 
						||
 | 
						||
<pre>
 | 
						||
function tax(price, taxRate) {
 | 
						||
  const totalCost = price * (1 + taxRate);
 | 
						||
  console.log(`The cost of ${this.item} is ${totalCost}`);
 | 
						||
}
 | 
						||
</pre>
 | 
						||
 | 
						||
<p>调用 <code>tax(10, 0.1)</code> 将输出 <code>"The cost of undefined is 11"</code> 。这是因为 <code>this</code> 上下文未定义。</p>
 | 
						||
 | 
						||
<p>然而,调用 <code>tax.callPolyfill({item: "salad"}, 10, 0.1)</code> 将输出 <code>"The cost of salad is 11"</code> 。<code>this</code> 上下文被正确设置,函数输出了适当的结果。</p>
 | 
						||
 | 
						||
<p>请在不使用内置的 <code>Function.call</code> 方法的情况下解决这个问题。</p>
 | 
						||
 | 
						||
<p> </p>
 | 
						||
 | 
						||
<p><strong class="example">示例 1:</strong></p>
 | 
						||
 | 
						||
<pre>
 | 
						||
<strong>输入:</strong>
 | 
						||
fn = function add(b) {
 | 
						||
  return this.a + b;
 | 
						||
}
 | 
						||
args = [{"a": 5}, 7]
 | 
						||
<b>输出:</b>12
 | 
						||
<strong>解释:</strong>
 | 
						||
fn.callPolyfill({"a": 5}, 7); // 12
 | 
						||
<code>callPolyfill </code>将 "this" 上下文设置为 <code>{"a": 5} </code>,并将 7 作为参数传递。
 | 
						||
</pre>
 | 
						||
 | 
						||
<p><strong class="example">示例 2:</strong></p>
 | 
						||
 | 
						||
<pre>
 | 
						||
<b>输入:</b>
 | 
						||
fn = function tax(price, taxRate) { 
 | 
						||
 return `The cost of the ${this.item} is ${price * taxRate}`; 
 | 
						||
}
 | 
						||
args = [{"item": "burger"}, 10, 1,1]
 | 
						||
<b>输出:</b>"The cost of the burger is 11"
 | 
						||
<b>解释:</b><code>callPolyfill </code>将 "this" 上下文设置为 <code>{"item": "burger"} </code>,并将 10 和 1.1 作为附加参数传递。
 | 
						||
</pre>
 | 
						||
 | 
						||
<p> </p>
 | 
						||
 | 
						||
<p><strong>提示:</strong></p>
 | 
						||
 | 
						||
<ul style="list-style-type:square;">
 | 
						||
	<li><code><font face="monospace">typeof args[0] == 'object' and args[0] != null</font></code></li>
 | 
						||
	<li><code>1 <= args.length <= 100</code></li>
 | 
						||
	<li><code>2 <= JSON.stringify(args[0]).length <= 10<sup>5</sup></code></li>
 | 
						||
</ul>
 |