blob: e5dee577bc13075db3d4cc00c34b44b80192261d (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
---
title: Expression closures
slug: Web/JavaScript/Reference/Operators/Expression_closures
tags:
- Functions
- JavaScript
- Reference
translation_of: Archive/Web/JavaScript/Expression_closures
---
<div class="warning"><strong>非标准,不要使用!</strong><br>
闭包表达式语法是废弃的 SpiderMonkey 的特性,并且<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1083458">将被移除</a>。为了长远使用,考虑使用<a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">箭头函数</a>。</div>
<div>{{jsSidebar("Operators")}}</div>
<p>表达式闭包是定义简单函数的一种便捷方式。</p>
<h2 id="语法">语法</h2>
<pre class="syntaxbox">function [<em>name</em>]([<em>param1</em>[, <em>param2[</em>, ..., <em>paramN</em>]]])
<em>expression</em>
</pre>
<h3 id="参数">参数</h3>
<dl>
<dt><code>name</code></dt>
<dd>函数名。函数名可以省略不写,称为匿名函数。函数名仅在函数体有效。</dd>
<dt><code>paramN</code></dt>
<dd>形参名。一个函数最多可以有255个参数。</dd>
<dt><code>expression</code></dt>
<dd>构成函数体的表达式。</dd>
</dl>
<h2 id="描述">描述</h2>
<p>这一附加特性只是编写简单函数的快捷方式,让语言更类似通常的 <a class="external" href="http://en.wikipedia.org/wiki/Lambda_calculus#Lambda_calculus_and_programming_languages">Lambda 标记</a>。</p>
<p>JavaScript 1.7 及之前版本:</p>
<pre class="brush: js">function(x) { return x * x; }</pre>
<p>JavaScript 1.8:</p>
<pre class="brush: js">function(x) x * x</pre>
<p>该语法支持省略花括号和'return'语句。使用这种编码的目的只是为了在句法上使得代码更加简化,但除此之外没有其他好处。</p>
<h2 id="示例">示例</h2>
<p>一种绑定事件监听器的便捷方式:</p>
<pre class="brush: js"> document.addEventListener("click", function() false, true);
</pre>
<p>在 JavaScript 1.6 中的一些数组函数中使用该标记:</p>
<pre class="brush: js">elems.some(function(elem) elem.type == "text");
</pre>
<h2 id="浏览器兼容">浏览器兼容</h2>
<div class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div>
<p>{{Compat("javascript.operators.expression_closures")}}</p>
<h2 id="相关链接">相关链接</h2>
<ul>
<li>{{jsxref("Functions_and_function_scope", "Functions and function scope")}}</li>
<li>{{jsxref("Function")}}</li>
<li>{{jsxref("Statements/function", "function statement")}}</li>
<li>{{jsxref("Operators/function", "function expression")}}</li>
<li>{{jsxref("Statements/function*", "function* statement")}}</li>
<li>{{jsxref("Operators/function*", "function* expression")}}</li>
<li>{{jsxref("GeneratorFunction")}}</li>
</ul>
|