From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../functions/arguments/callee/index.html | 197 +++++++++++++++++ .../reference/functions/arguments/index.html | 235 +++++++++++++++++++++ 2 files changed, 432 insertions(+) create mode 100644 files/zh-tw/web/javascript/reference/functions/arguments/callee/index.html create mode 100644 files/zh-tw/web/javascript/reference/functions/arguments/index.html (limited to 'files/zh-tw/web/javascript/reference/functions/arguments') diff --git a/files/zh-tw/web/javascript/reference/functions/arguments/callee/index.html b/files/zh-tw/web/javascript/reference/functions/arguments/callee/index.html new file mode 100644 index 0000000000..397eb08d00 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/functions/arguments/callee/index.html @@ -0,0 +1,197 @@ +--- +title: arguments.callee +slug: Web/JavaScript/Reference/Functions/arguments/callee +translation_of: Web/JavaScript/Reference/Functions/arguments/callee +--- +
{{jsSidebar("Functions")}}
+ +

The arguments.callee property contains the currently executing function.

+ +

描述

+ +

callee is a property of the arguments object. It can be used to refer to the currently executing function inside the function body of that function. This is useful when the name of the function is unknown, such as within a function expression with no name (also called "anonymous functions").

+ +
Warning: The 5th edition of ECMAScript (ES5) forbids use of arguments.callee() in strict mode. Avoid using arguments.callee() by either giving function expressions a name or use a function declaration where a function must call itself.
+ +

Why was arguments.callee removed from ES5 strict mode?

+ +

(adapted from a Stack Overflow answer by olliej)

+ +

Early versions of JavaScript did not allow named function expressions, and for this reason you could not make a recursive function expression.

+ +

For example, this syntax worked:

+ +
function factorial (n) {
+    return !(n > 1) ? 1 : factorial(n - 1) * n;
+}
+
+[1,2,3,4,5].map(factorial);
+ +

but:

+ +
[1,2,3,4,5].map(function (n) {
+    return !(n > 1) ? 1 : /* what goes here? */ (n - 1) * n;
+});
+ +

did not. To get around this arguments.callee was added so you could do

+ +
[1,2,3,4,5].map(function (n) {
+    return !(n > 1) ? 1 : arguments.callee(n - 1) * n;
+});
+ +

However, this was actually a really bad solution as this (in conjunction with other arguments, callee, and caller issues) make inlining and tail recursion impossible in the general case (you can achieve it in select cases through tracing, etc., but even the best code is suboptimal due to checks that would not otherwise be necessary.) The other major issue is that the recursive call will get a different this value, e.g.:

+ +
var global = this;
+
+var sillyFunction = function (recursed) {
+    if (!recursed) { return arguments.callee(true); }
+    if (this !== global) {
+        alert("This is: " + this);
+    } else {
+        alert("This is the global");
+    }
+}
+
+sillyFunction();
+ +

ECMAScript 3 resolved these issues by allowing named function expressions. For example:

+ +
[1,2,3,4,5].map(function factorial (n) {
+    return !(n > 1) ? 1 : factorial(n-1)*n;
+});
+ +

This has numerous benefits:

+ + + +

Another feature that was deprecated was arguments.callee.caller, or more specifically Function.caller. Why is this? Well, at any point in time you can find the deepest caller of any function on the stack, and as I said above looking at the call stack has one single major effect: it makes a large number of optimizations impossible, or much much more difficult. For example, if you cannot guarantee that a function f will not call an unknown function, it is not possible to inline f. Basically it means that any call site that may have been trivially inlinable accumulates a large number of guards:

+ +
function f (a, b, c, d, e) { return a ? b * c : d * e; }
+ +

If the JavaScript interpreter cannot guarantee that all the provided arguments are numbers at the point that the call is made, it needs to either insert checks for all the arguments before the inlined code, or it cannot inline the function. Now in this particular case a smart interpreter should be able to rearrange the checks to be more optimal and not check any values that would not be used. However in many cases that's just not possible and therefore it becomes impossible to inline.

+ +

範例

+ +

Using arguments.callee in an anonymous recursive function

+ +

A recursive function must be able to refer to itself. Typically, a function refers to itself by its name. However, an anonymous function (which can be created by a function expression or the Function constructor) does not have a name. Therefore if there is no accessible variable referring to it, the only way the function can refer to itself is by arguments.callee.

+ +

The following example defines a function, which, in turn, defines and returns a factorial function. This example isn't very practical, and there are nearly no cases where the same result cannot be achieved with named function expressions.

+ +
function create() {
+   return function(n) {
+      if (n <= 1)
+         return 1;
+      return n * arguments.callee(n - 1);
+   };
+}
+
+var result = create()(5); // returns 120 (5 * 4 * 3 * 2 * 1)
+ +

A use of arguments.callee with no good alternative

+ +

However, in a case like the following, there are not alternatives to arguments.callee, so its deprecation could be a bug (see {{Bug("725398")}}):

+ +
function createPerson (sIdentity) {
+    var oPerson = new Function("alert(arguments.callee.identity);");
+    oPerson.identity = sIdentity;
+    return oPerson;
+}
+
+var john = createPerson("John Smith");
+
+john();
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.2
{{SpecName('ES5.1', '#sec-10.6', 'Arguments Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/functions/arguments/index.html b/files/zh-tw/web/javascript/reference/functions/arguments/index.html new file mode 100644 index 0000000000..6b1d6a45a1 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/functions/arguments/index.html @@ -0,0 +1,235 @@ +--- +title: Arguments 物件 +slug: Web/JavaScript/Reference/Functions/arguments +tags: + - Functions + - JavaScript + - Reference + - arguments +translation_of: Web/JavaScript/Reference/Functions/arguments +--- +
+
{{jsSidebar("Functions")}}
+
+ +

arguments 物件是一個對應傳入函式之引數的類陣列(Array-like)物件。

+ +

語法

+ +
arguments
+ +

描述

+ +
+

Note: 如果你有在使用 ES6 語法,建議參考其餘參數

+
+ +
+

Note: 「類陣列 (Array-like)」 的意思是 arguments 一樣擁有 length這項屬性,以及從 0 開始的索引,但是它沒有陣列內建的方法像是 forEach() ,或是 map() 。

+
+ +

The arguments object is a local variable available within all (non-arrow) functions. You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0.

+ +

For example, if a function is passed three arguments, you can refer to them as follows:

+ +
arguments[0]
+arguments[1]
+arguments[2]
+
+ +

arguments 也可以被指定:

+ +
arguments[1] = 'new value';
+ +

arguments 物件不是陣列。它與陣列非常相似,但是它沒有除了 length 這個屬性以外的其他陣列屬性。舉例,它沒有 pop 這個陣列方法。

+ +

然而,它依然可以被轉換為真正的陣列(Array)。

+ +
var args = Array.prototype.slice.call(arguments);
+var args = [].slice.call(arguments);
+
+// ES2015
+const args = Array.from(arguments);
+
+ +
+

Using slice on arguments prevents optimizations in some JavaScript engines (V8 for example - more information). If you care for them, try constructing a new array by iterating through the arguments object instead. An alternative would be to use the despised Array constructor as a function:

+ +
var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));
+
+ +

You can use the arguments object if you call a function with more arguments than it is formally declared to accept. This technique is useful for functions that can be passed a variable number of arguments. Use arguments.length to determine the number of arguments passed to the function, and then process each argument by using the arguments object. To determine the number of parameters in the function signature, use the Function.length property.

+ +

Using typeof with Arguments

+ +

The typeof arguments returns 'object'. 

+ +
console.log(typeof arguments); // 'object' 
+ +

The typeof individual arguments can be determined with the use of indexing.

+ +
console.log(typeof arguments[0]); //this will return the typeof individual arguments.
+ +

Using the Spread Syntax with Arguments

+ +

You can also use the {{jsxref("Array.from()")}} method or the spread operator to convert arguments to a real Array:

+ +
var args = Array.from(arguments);
+var args = [...arguments];
+
+ +

屬性

+ +
+
arguments.callee
+
Reference to the currently executing function.
+
arguments.caller {{ Obsolete_inline() }}
+
Reference to the function that invoked the currently executing function.
+
arguments.length
+
Reference to the number of arguments passed to the function.
+
arguments[@@iterator]
+
Returns a new Array Iterator object that contains the values for each index in the arguments.
+
+ +

範例

+ +

Defining a function that concatenates several strings

+ +

This example defines a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:

+ +
function myConcat(separator) {
+  var args = Array.prototype.slice.call(arguments, 1);
+  return args.join(separator);
+}
+ +

You can pass any number of arguments to this function, and it creates a list using each argument as an item in the list.

+ +
// returns "red, orange, blue"
+myConcat(', ', 'red', 'orange', 'blue');
+
+// returns "elephant; giraffe; lion; cheetah"
+myConcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah');
+
+// returns "sage. basil. oregano. pepper. parsley"
+myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley');
+ +

Defining a function that creates HTML lists

+ +

This example defines a function that creates a string containing HTML for a list. The only formal argument for the function is a string that is "u" if the list is to be unordered (bulleted), or "o" if the list is to be ordered (numbered). The function is defined as follows:

+ +
function list(type) {
+  var result = '<' + type + 'l><li>';
+  var args = Array.prototype.slice.call(arguments, 1);
+  result += args.join('</li><li>');
+  result += '</li></' + type + 'l>'; // end list
+
+  return result;
+}
+ +

You can pass any number of arguments to this function, and it adds each argument as an item to a list of the type indicated. For example:

+ +
var listHTML = list('u', 'One', 'Two', 'Three');
+
+/* listHTML is:
+
+"<ul><li>One</li><li>Two</li><li>Three</li></ul>"
+
+*/
+ +

Rest, default, and destructured parameters

+ +

The arguments object can be used in conjunction with rest, default, and destructured parameters.

+ +
function foo(...args) {
+  return args;
+}
+foo(1, 2, 3); // [1,2,3]
+
+ +

While the presence of restdefault, or destructured parameters does not alter the behavior of the arguments object in strict mode code, there is a subtle difference for non-strict code.

+ +

When a non-strict function does not contain restdefault, or destructured parameters, then the values in the arguments object do track the values of the arguments (and vice versa). See the code below:

+ +
function func(a) {
+  arguments[0] = 99; // updating arguments[0] also updates a
+  console.log(a);
+}
+func(10); // 99
+
+ +

and

+ +
function func(a) {
+  a = 99; // updating a also updates arguments[0]
+  console.log(arguments[0]);
+}
+func(10); // 99
+
+ +

When a non-strict function does contain restdefault, or destructured parameters, then the values in the arguments object do not track the values of the arguments (and vice versa). Instead, they reflect the arguments provided at the time of invocation:

+ +
function func(a = 55) {
+  arguments[0] = 99; // updating arguments[0] does not also update a
+  console.log(a);
+}
+func(10); // 10
+ +

and

+ +
function func(a = 55) {
+  a = 99; // updating a does not also update arguments[0]
+  console.log(arguments[0]);
+}
+func(10); // 10
+
+ +

and

+ +
function func(a = 55) {
+  console.log(arguments[0]);
+}
+func(); // undefined
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1
{{SpecName('ES5.1', '#sec-10.6', 'Arguments Object')}}{{Spec2('ES5.1')}}
{{SpecName('ES2015', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ES2015')}}
{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.functions.arguments")}}

+ +

參見

+ + -- cgit v1.2.3-54-g00ecf