253 lines
18 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<article id="wikiArticle">
<div></div>
<p><strong><code>Function</code> 构造函数</strong> 创建一个新的Function对象。 在 JavaScript 中, 每个函数实际上都是一个<code>Function对象。</code></p>
<div><iframe class="interactive interactive-js" frameborder="0" height="250" src="https://interactive-examples.mdn.mozilla.net/pages/js/function-constructor.html" width="100%"></iframe></div>
<p class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a class="external" href="https://github.com/mdn/interactive-examples" rel="noopener">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p>
<h2 id="Syntax" name="Syntax">语法</h2>
<pre><code class="language-javascript"><code>new Function ([<em>arg1</em>[, <em>arg2</em>[, ...<em>argN</em>]],] <em>functionBody</em>)</code></code></pre>
<h3 id="Parameters" name="Parameters">参数</h3>
<dl>
<dt>arg1, arg2, ... arg<em>N</em></dt>
<dd>被函数使用的参数的名称必须是合法命名的。参数名称是一个有效的JavaScript标识符的字符串或者一个用逗号分隔的有效字符串的列表;例如“דtheValue”或“AB”。</dd>
<dt>functionBody</dt>
<dd>一个含有包括函数定义的JavaScript语句的<strong>字符串</strong></dd>
</dl>
<h2 id="Description" name="Description">描述</h2>
<p><code>使用Function<font face="Open Sans, sans-serif">构造器生成的</font></code><code>Function对象是在函数创建时解析的。这比你使用<a href="Reference/Operators/function">函数声明</a>或者<a href="Reference/Operators/function">函数表达式</a>(function)并在你的代码中调用更为低效,因为使用后者创建的函数是跟其他代码一起解析的</code></p>
<p>所有被传递到构造函数中的参数,都将被视为将被创建的函数的参数,并且是相同的标示符名称和传递顺序。</p>
<div class="note">
<p><strong>注意: </strong>使用Function构造器生成的函数并不会在创建它们的上下文中创建闭包它们一般<u><strong>在全局作用域中被创建</strong></u>。当运行这些函数的时候它们只能访问自己的本地变量和全局变量不能访问Function构造器被调用生成的上下文的作用域。这和使用带有函数表达式代码的 <a href="Reference/eval" title="此页面仍未被本地化, 期待您的翻译!"><code>eval</code></a> 不同。<a href="Reference/Global_Objects/eval"><span style="display: none;"> </span></a></p>
</div>
<p>以调用函数的方式调用Function的构造函数 (不是用new关键字) 跟以构造函数来调用是一样的.</p>
<h2 id="属性和方法">属性和方法</h2>
<p>全局的Function对象没有自己的属性和方法, 但是, 因为它本身也是函数,所以它也会通过原型链从<a href="Reference/Global_Objects/Function/prototype" title="Function.prototype 属性存储了 Function 的原型对象。"><code>Function.prototype</code></a>上继承部分属性和方法。</p>
<h2 id="原型对象"><font face="Consolas, Monaco, Andale Mono, monospace">原型对象</font></h2>
<h3 id="属性">属性</h3>
<div><dl>
<dt><a href="Reference/Global_Objects/Function/arguments" title="function.arguments 属性代表传入函数的实参,它是一个类数组对象。"><code>Function.arguments</code></a> <span title="This deprecated API should no longer be used, but will probably still work."><i class="icon-thumbs-down-alt"> </i></span></dt>
<dd>以数组形式获取传入函数的所有参数。此属性已被<a href="Reference/Functions_and_function_scope/arguments" title="此页面仍未被本地化, 期待您的翻译!"><code>arguments</code></a>替代。</dd>
<dt><s class="obsoleteElement"><a href="Reference/Global_Objects/Function/arity" title="返回一个函数的形参数量."><code>Function.arity</code></a> <span class="icon-only-inline" title="This is an obsolete API and is no longer guaranteed to work."><i class="icon-trash"> </i></span></s></dt>
<dd><s class="obsoleteElement">用于指定的函数的参数的个数,但已被删除。使用<a href="Reference/Global_Objects/Function/length" title="此页面仍未被本地化, 期待您的翻译!"><code>length</code></a>属性代替。</s></dd>
<dt><a href="Reference/Global_Objects/Function/caller" title="返回调用指定函数的函数."><code>Function.caller</code></a> <span class="icon-only-inline" title="This API has not been standardized."><i class="icon-warning-sign"> </i></span></dt>
<dd>获取调用函数的具体对象。</dd>
<dt><a href="Reference/Global_Objects/Function/length" title="此页面仍未被本地化, 期待您的翻译!"><code>Function.length</code></a></dt>
<dd>获取函数的接收参数个数。</dd>
<dt><a href="Reference/Global_Objects/Function/name" title="name 属性返回一个函数声明的名称。"><code>Function.name</code></a> <span class="icon-only-inline" title="This API has not been standardized."><i class="icon-warning-sign"> </i></span></dt>
<dd>获取函数的名称。</dd>
<dt><a href="Reference/Global_Objects/Function/displayName" title="function.displayName 属性获取函数的显示名称"><code>Function.displayName</code></a> <span class="icon-only-inline" title="This API has not been standardized."><i class="icon-warning-sign"> </i></span></dt>
<dd>获取函数的display name。</dd>
<dt><code>Function.prototype.constructor</code></dt>
<dd>声明函数的原型构造方法,详细请参考 <a href="Reference/Global_Objects/Object/constructor" title='返回创建实例对象的 Object 构造函数的引用。注意此属性的值是对函数本身的引用而不是一个包含函数名称的字符串。对原始类型来说如1true和"test",该值只可读。'><code>Object.constructor</code></a></dd>
</dl></div>
<h3 id="Methods" name="Methods">方法</h3>
<div><dl>
<dt><a href="Reference/Global_Objects/Function/apply" title="apply() 方法调用一个具有给定this值的函数以及作为一个数组或类似数组对象提供的参数。"><code>Function.prototype.apply()</code></a></dt>
<dd>在一个对象的上下文中应用另一个对象的方法;参数能够以数组形式传入。</dd>
<dt><a href="Reference/Global_Objects/Function/bind" title="bind()方法创建一个新的函数在调用时设置this关键字为提供的值。并在调用新函数时将给定参数列表作为原函数的参数序列的前若干项。"><code>Function.prototype.bind()</code></a></dt>
<dd><span style="font-family: courier new,andale mono,monospace; line-height: 1.5;">bind()</span>方法会创建一个新函数,称为绑定函数.当调用这个绑定函数时,绑定函数会以创建它时传入 <span style="font-family: courier new,andale mono,monospace;">bind()</span>方法的第一个参数作为 <span style="font-family: courier new,andale mono,monospace;">this</span>,传入 <span style="font-family: courier new,andale mono,monospace;">bind()</span>方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数.</dd>
<dt><a href="Reference/Global_Objects/Function/call" title="call() 方法调用一个函数, 其具有一个指定的this值和分别地提供的参数(参数的列表)。"><code>Function.prototype.call()</code></a></dt>
<dd>在一个对象的上下文中应用另一个对象的方法;参数能够以列表形式传入。</dd>
<dt><a href="Reference/Global_Objects/Function/isGenerator" title="判断一个函数是否是一个生成器."><code>Function.prototype.isGenerator()</code></a> <span class="icon-only-inline" title="This API has not been standardized."><i class="icon-warning-sign"> </i></span></dt>
<dd><code>若函数对象为</code><a href="Guide/Iterators_and_Generators">generator</a>返回true反之返回 <code>false</code></dd>
<dt><a href="Reference/Global_Objects/Function/toSource" title="返回函数的源代码的字符串表示."><code>Function.prototype.toSource()</code></a> <span class="icon-only-inline" title="This API has not been standardized."><i class="icon-warning-sign"> </i></span></dt>
<dd>获取函数的实现源码的字符串。 覆盖了 <a href="Reference/Global_Objects/Object/toSource" title="toSource()方法返回一个表示对象源代码的字符串。"><code>Object.prototype.toSource</code></a> 方法。</dd>
<dt><a href="Reference/Global_Objects/Function/toString" title="toString() 方法返回一个表示当前函数源代码的字符串。"><code>Function.prototype.toString()</code></a></dt>
<dd>获取函数的实现源码的字符串。覆盖了 <a href="Reference/Global_Objects/Object/toString" title="toString() 方法返回一个表示该对象的字符串。"><code>Object.prototype.toString</code></a> 方法。</dd>
</dl></div>
<h2 id="Function_instances" name="Function_instances"><font face="Consolas, Monaco, Andale Mono, monospace">实例</font></h2>
<p><code>Function</code> 实例从 <a href="Reference/Global_Objects/Function/prototype" title="Function.prototype 属性存储了 Function 的原型对象。"><code>Function.prototype</code></a> 继承了一些属性和方法。 同其他构造函数一样, 你可以改变构造函数的原型从而使得所有的Function实例的属性和方法发生改变。</p>
<h2 id="Example.3A_Specifying_arguments_with_the_Function_constructor" name="Example.3A_Specifying_arguments_with_the_Function_constructor">示例</h2>
<h3 id="Example.3A_Specifying_arguments_with_the_Function_constructor" name="Example.3A_Specifying_arguments_with_the_Function_constructor">传入参数调用Function构造函数</h3>
<p>下面的代码会创建一个需要两个参数的Function对象</p>
<pre><code class="language-javascript">// 可以直接运行在 JavaScript 控制的代码例子
// 创建了一个能返回两个参数和的函数
const adder = new Function("a", "b", "return a + b");
// 调用函数
adder(2, 6);
// 8</code></pre>
<p>参数"a"和"b"是参数的名字,在函数体中被使用,"<code>return a + b</code>"。</p>
<h3 id="Function构造器生成的函数在全局作用域中被创建">Function构造器生成的函数在全局作用域中被创建</h3>
<pre><code class="language-javascript"><strong>// 1、f()函数返回的function e()是闭包.</strong>
var n = 1;
function f(){
var n = 2;
function e(){
return n;
}
return e;
}
console.log (f()()); //2
<strong>// 2、f()函数返回的function e()是全局作用域函数</strong>
var n = 1;
function f(){
var n = 2;
var e = new Function("return n;");
return e;
}
console.log (f()()); //1</code></pre>
<h3 id="Example" name="Example">大量修改DOM元素的递归快捷方式</h3>
<p>使用 Function 构造器创建函数是从一个函数中动态地创建一些不确定数量的有可执行代码的在全局范围里可用的新对象的方式之一。在下面的例子中,如果你不想使用闭包,那么每创建一个新的查询函数都不可避免地要调用 Function 构造器。</p>
<pre><code class="language-html">&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;
&lt;title&gt;MDN Example - a recursive shortcut to massively modify the DOM&lt;/title&gt;
&lt;script type="text/javascript"&gt;
var domQuery = (function() {
var aDOMFunc = [
Element.prototype.removeAttribute,
Element.prototype.setAttribute,
CSSStyleDeclaration.prototype.removeProperty,
CSSStyleDeclaration.prototype.setProperty
];
function setSomething (bStyle, sProp, sVal) {
var bSet = Boolean(sVal), fAction = aDOMFunc[bSet | bStyle &lt;&lt; 1],
aArgs = Array.prototype.slice.call(arguments, 1, bSet ? 3 : 2),
aNodeList = bStyle ? this.cssNodes : this.nodes;
if (bSet &amp;&amp; bStyle) { aArgs.push(""); }
for (
var nItem = 0, nLen = this.nodes.length;
nItem &lt; nLen;
fAction.apply(aNodeList[nItem++], aArgs)
);
this.follow = setSomething.caller;
return this;
}
function setStyles (sProp, sVal) { return setSomething.call(this, true, sProp, sVal); }
function setAttribs (sProp, sVal) { return setSomething.call(this, false, sProp, sVal); }
function getSelectors () { return this.selectors; };
function getNodes () { return this.nodes; };
return (function (sSelectors) {
var oQuery = new Function('return arguments.callee.follow.apply(arguments.callee, arguments);');
oQuery.selectors = sSelectors;
oQuery.nodes = document.querySelectorAll(sSelectors);
oQuery.cssNodes = Array.prototype.map.call(oQuery.nodes, function (oInlineCSS) { return oInlineCSS.style; });
oQuery.attributes = setAttribs;
oQuery.inlineStyle = setStyles;
oQuery.follow = getNodes;
oQuery.toString = getSelectors;
oQuery.valueOf = getNodes;
return oQuery;
});
})();
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div class="testClass"&gt;Lorem ipsum&lt;/div&gt;
&lt;p&gt;Some text&lt;/p&gt;
&lt;div class="testClass"&gt;dolor sit amet&lt;/div&gt;
&lt;script type="text/javascript"&gt;
  domQuery('.testClass')
   .attributes('lang', 'en')('title', 'Risus abundat in ore stultorum')
    .inlineStyle('background-color', 'black')('color', 'white')('width', '100px')('height', '50px');
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h2 id="规范">规范</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
<tr>
<td><a class="external" href="https://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%201st%20edition,%20June%201997.pdf" hreflang="en" lang="en" rel="noopener" title="ECMAScript 1st Edition (ECMA-262)">ECMAScript 1st Edition (ECMA-262)</a></td>
<td><span class="spec-Standard">Standard</span></td>
<td>Initial definition. Implemented in JavaScript 1.0.</td>
</tr>
<tr>
<td><a class="external" href="https://www.ecma-international.org/ecma-262/5.1/#sec-15.3" hreflang="en" lang="en" rel="noopener">ECMAScript 5.1 (ECMA-262)<br/><small lang="zh-CN">Function</small></a></td>
<td><span class="spec-Standard">Standard</span></td>
<td> </td>
</tr>
<tr>
<td><a class="external" href="https://www.ecma-international.org/ecma-262/6.0/#sec-function-objects" hreflang="en" lang="en" rel="noopener">ECMAScript 2015 (6th Edition, ECMA-262)<br/><small lang="zh-CN">Function</small></a></td>
<td><span class="spec-Standard">Standard</span></td>
<td> </td>
</tr>
</tbody>
</table>
<h2 id="浏览器支持">浏览器支持</h2>
<div><div class="blockIndicator warning"><strong><a class="external" href="https://github.com/mdn/browser-compat-data" rel="noopener">We're converting our compatibility data into a machine-readable JSON format</a></strong>.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
<strong><a class="new" href="/zh-CN/docs/MDN/Contribute/Structures/Compatibility_tables" rel="nofollow">Find out how you can help!</a></strong></div>
<div class="htab">
<a id="AutoCompatibilityTable" name="AutoCompatibilityTable"></a>
<ul>
<li class="selected"><a>Desktop</a></li>
<li><a>Mobile</a></li>
</ul>
</div></div>
<div id="compat-desktop">
<table class="compat-table">
<tbody>
<tr>
<th>Feature</th>
<th>Chrome</th>
<th>Firefox (Gecko)</th>
<th>Internet Explorer</th>
<th>Opera</th>
<th>Safari</th>
</tr>
<tr>
<td>Basic support</td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
</tr>
</tbody>
</table>
</div>
<div id="compat-mobile">
<table class="compat-table">
<tbody>
<tr>
<th>Feature</th>
<th>Android</th>
<th>Chrome for Android</th>
<th>Firefox Mobile (Gecko)</th>
<th>IE Mobile</th>
<th>Opera Mobile</th>
<th>Safari Mobile</th>
</tr>
<tr>
<td>Basic support</td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
</tr>
</tbody>
</table>
</div>
<h2 id="See_also" name="See_also">相关链接</h2>
<ul>
<li><a href="Reference/Functions" title="有关更多示例和说明请参阅有关函数的JavaScript指南。"><code>Functions and function scope</code></a></li>
<li><a href="Reference/Function" title="此页面仍未被本地化, 期待您的翻译!"><code>Function</code></a></li>
<li><a href="Reference/Statements/function" title="函数声明定义一个具有指定参数的函数。"><code>function statement</code></a></li>
<li><a href="Reference/Operators/function" title="function 关键字可以用来在一个表达式中定义一个函数。"><code>function expression</code></a></li>
<li><a href="Reference/Statements/function*" title="function* 这种声明方式(function关键字后跟一个星号会定义一个生成器函数 (generator function),它返回一个  Generator  对象。"><code>function* statement</code></a></li>
<li><a href="Reference/Operators/function*" title="function*关键字可以在表达式内部定义一个生成器函数。"><code>function* expression</code></a></li>
<li><a href="Reference/Global_Objects/GeneratorFunction" title="GeneratorFunction构造器生成新的生成器函数 对象。在JavaScript中生成器函数实际上都是GeneratorFunction的实例对象。"><code>GeneratorFunction</code></a></li>
<li>CSP: https://developers.google.com/web/fundamentals/security/csp/#eval</li>
<li>CSP: https://gist.github.com/xgqfrms-GitHub/ecf7733d066d56723b00de41a849037a</li>
</ul>
</article>