From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../global_objects/function/apply/index.html | 260 +++++++++++++++++ .../global_objects/function/bind/index.html | 321 +++++++++++++++++++++ .../global_objects/function/call/index.html | 105 +++++++ .../reference/global_objects/function/index.html | 191 ++++++++++++ .../global_objects/function/length/index.html | 144 +++++++++ .../global_objects/function/prototype/index.html | 138 +++++++++ 6 files changed, 1159 insertions(+) create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/apply/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/bind/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/call/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/length/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/prototype/index.html (limited to 'files/zh-tw/web/javascript/reference/global_objects/function') diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/apply/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/apply/index.html new file mode 100644 index 0000000000..698d2f46fc --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/apply/index.html @@ -0,0 +1,260 @@ +--- +title: Function.prototype.apply() +slug: Web/JavaScript/Reference/Global_Objects/Function/apply +translation_of: Web/JavaScript/Reference/Global_Objects/Function/apply +--- +
{{JSRef}}
+ +

apply() 方法會呼叫一個以 this 的代表值和一個陣列形式的值組(或是一個 array-like object )為參數的函式。

+ +
+

注意:這個函式的語法和{{jsxref("Function.call", "call()")}} 幾乎一樣,最大的不同是 call() 接受一連串的參數,而 apply() 接受一組陣列形式的參數

+
+ +

語法

+ +
fun.apply(thisArg, [argsArray])
+ +

參數

+ +
+
thisArg
+
讓 fun 呼叫時可以視為 this  的值。注意,這可能並不是最後會在方法裡看見的值:如果這是一個在非 {{jsxref("Strict_mode", "non-strict mode", "", 1)}} 下運作的程式碼,{{jsxref("null")}} 及 {{jsxref("undefined")}} 將會被全域物件取代,而原始類別將被封裝。
+
argsArray
+
一個 array-like object ,定義了 fun 要呼叫的一組參數,如果沒有需要提供,可以傳入 {{jsxref("null")}} 或 {{jsxref("undefined")}} 。從 ECMAScript 5 開始,這些參數不僅可以是泛型的 array-like object ,而不一定要是一組陣列。查看下方的{{anch("Browser_compatibility", "browser compatibility")}} 資訊。
+
+ +

回傳值

+ +

傳入 this 值及一組參數後得到的結果。

+ +

描述

+ +

在呼叫一個現存的函式時,你可以傳入不同的 this 物件值。this 參考到現在的物件,也就是正在執行的物件。apply 讓你可以只寫一次方法後,讓其他物件也繼承到這個方法,而不用一再重寫。

+ +

apply 與 {{jsxref("Function.call", "call()")}} 非常相似,不同的是支援的傳入參數類型。使用陣列形式的參數,而不是命名過的接收參數。使用 apply 時,你可以選擇使用陣列實字:fun.apply(this, ['eat', 'bananas']); 或是 {{jsxref("Array")}} 物件: fun.apply(this, new Array('eat', 'bananas'))。

+ +

除此之外,你也可以使用 {{jsxref("Functions/arguments", "arguments")}} 代表 argsArray 參數。arguments 是在函式裡的區域變數,可用來存取所有沒有特別被所呼叫物件指定的傳入參數。因此,使用 apply 時你不需要知道所呼叫函式的指定參數。使用 arguments 把所有參數傳入呼叫的方法裡,而被呼叫的方法會接手處理這些參數。

+ +

從 ECMAScript 5th 版本後,也可以使用陣列形式的物件,在實踐上這代表他會擁有 length 以及整數範圍  (0...length-1) 的屬性。舉例來說,你可以使用 {{domxref("NodeList")}}  或是一個像這樣的自定義屬性: { 'length': 2, '0': 'eat', '1': 'bananas' }。

+ +
+

一般瀏覽器,包括 Chrome 14 及 Internet Explorer 9,仍不支援陣列形式的物件,所以會對此丟出一個錯誤。

+
+ +

範例

+ +

使用 apply 與建構子鏈結

+ +

您可以使用 apply 鏈結 {{jsxref("Operators/new", "constructors", "", 1)}} 一個物件,與 Java 相似,如下範例中我們可以建立一個全域的 {{jsxref("Function")}} 方法叫 construct,使您可以使用類陣列的物件與建構子去替代參數列表。

+ +
Function.prototype.construct = function(aArgs) {
+  var oNew = Object.create(this.prototype);
+  this.apply(oNew, aArgs);
+  return oNew;
+};
+
+ +
+

注意:如上範例的 Object.create() 方法是屬於比較新的寫法。如需使用閉包的替代方法,請參考以下的範例:

+ +
Function.prototype.construct = function(aArgs) {
+  var fConstructor = this, fNewConstr = function() {
+    fConstructor.apply(this, aArgs);
+  };
+  fNewConstr.prototype = fConstructor.prototype;
+  return new fNewConstr();
+};
+
+ +

使用範例:

+ +
function MyConstructor() {
+  for (var nProp = 0; nProp < arguments.length; nProp++) {
+    this['property' + nProp] = arguments[nProp];
+  }
+}
+
+var myArray = [4, 'Hello world!', false];
+var myInstance = MyConstructor.construct(myArray);
+
+console.log(myInstance.property1);                // logs 'Hello world!'
+console.log(myInstance instanceof MyConstructor); // logs 'true'
+console.log(myInstance.constructor);              // logs 'MyConstructor'
+
+ +
+

注意:This non-native Function.construct method will not work with some native constructors (like {{jsxref("Date")}}, for example). In these cases you have to use the {{jsxref("Function.prototype.bind")}} method (for example, imagine having an array like the following, to be used with {{jsxref("Global_Objects/Date", "Date")}} constructor: [2012, 11, 4]; in this case you have to write something like: new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))() — anyhow this is not the best way to do things and probably should not be used in any production environment).

+
+ +

使用 apply 於內建的函數

+ +

apply 可以巧妙的在某些任務中使用內建函數,否則可能會循環遍歷整個陣列來寫入。如下範例,我們使用 Math.max/Math.min 來找出陣列中最大/最小的值。

+ +
// min/max number in an array
+var numbers = [5, 6, 2, 3, 7];
+
+// using Math.min/Math.max apply
+var max = Math.max.apply(null, numbers);
+// This about equal to Math.max(numbers[0], ...)
+// or Math.max(5, 6, ...)
+
+var min = Math.min.apply(null, numbers);
+
+// vs. simple loop based algorithm
+max = -Infinity, min = +Infinity;
+
+for (var i = 0; i < numbers.length; i++) {
+  if (numbers[i] > max) {
+    max = numbers[i];
+  }
+  if (numbers[i] < min) {
+    min = numbers[i];
+  }
+}
+
+ +

But beware: in using apply this way, you run the risk of exceeding the JavaScript engine's argument length limit. The consequences of applying a function with too many arguments (think more than tens of thousands of arguments) vary across engines (JavaScriptCore has hard-coded argument limit of 65536), because the limit (indeed even the nature of any excessively-large-stack behavior) is unspecified. Some engines will throw an exception. More perniciously, others will arbitrarily limit the number of arguments actually passed to the applied function. (To illustrate this latter case: if such an engine had a limit of four arguments [actual limits are of course significantly higher], it would be as if the arguments 5, 6, 2, 3 had been passed to apply in the examples above, rather than the full array.) If your value array might grow into the tens of thousands, use a hybrid strategy: apply your function to chunks of the array at a time:

+ +
function minOfArray(arr) {
+  var min = Infinity;
+  var QUANTUM = 32768;
+
+  for (var i = 0, len = arr.length; i < len; i += QUANTUM) {
+    var submin = Math.min.apply(null,
+                                arr.slice(i, Math.min(i+QUANTUM, len)));
+    min = Math.min(submin, min);
+  }
+
+  return min;
+}
+
+var min = minOfArray([5, 6, 2, 3, 7]);
+
+ +

Using apply in "monkey-patching"

+ +

Apply can be the best way to monkey-patch a built-in function of Firefox, or JS libraries. Given someobject.foo function, you can modify the function in a somewhat hacky way, like so:

+ +
var originalfoo = someobject.foo;
+someobject.foo = function() {
+  // Do stuff before calling function
+  console.log(arguments);
+  // Call the function as it would have been called normally:
+  originalfoo.apply(this, arguments);
+  // Run stuff after, here.
+}
+
+ +

This method is especially handy where you want to debug events, or interface with something that has no API like the various .on([event]... events, such as those usable on the Devtools Inspector).

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.3.4.3', 'Function.prototype.apply')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/bind/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/bind/index.html new file mode 100644 index 0000000000..7092477133 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/bind/index.html @@ -0,0 +1,321 @@ +--- +title: Function.prototype.bind() +slug: Web/JavaScript/Reference/Global_Objects/Function/bind +translation_of: Web/JavaScript/Reference/Global_Objects/Function/bind +--- +
{{JSRef}}
+ +

bind() 方法,會建立一個新函式。該函式被呼叫時,會將 this 關鍵字設為給定的參數,並在呼叫時,帶有提供之前,給定順序的參數。

+ +

語法

+ +
fun.bind(thisArg[, arg1[, arg2[, ...]]])
+ +

參數

+ +
+
thisArg
+
The value to be passed as the this parameter to the target function when the bound function is called. The value is ignored if the bound function is constructed using the {{jsxref("Operators/new", "new")}} operator.
+
arg1, arg2, ...
+
Arguments to prepend to arguments provided to the bound function when invoking the target function.
+
+ +

回傳值

+ +

A copy of the given function with the specified this value and initial arguments.

+ +

敘述

+ +

bind() 函式建立了一個新的綁定函式(BF)BF 是個包裝了原有函式物件的 exotic function objectECMAScript 2015 的術語)。通常,呼叫 BF 會執行該 wrapped function BF 含有以下內部屬性:

+ + + +

When bound function is called, it calls internal method [[Call]] on [[BoundTargetFunction]], with following arguments Call(boundThis, args). Where, boundThis is [[BoundThis]], args is [[BoundArguments]] followed by the arguments passed by the function call.

+ +

A bound function may also be constructed using the new operator: doing so acts as though the target function had instead been constructed. The provided this value is ignored, while prepended arguments are provided to the emulated function.

+ +

範例

+ +

建立綁定函式

+ +

The simplest use of bind() is to make a function that, no matter how it is called, is called with a particular this value. A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this (e.g. by using that method in callback-based code). Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem:

+ +
this.x = 9;    // this refers to global "window" object here in the browser
+var module = {
+  x: 81,
+  getX: function() { return this.x; }
+};
+
+module.getX(); // 81
+
+var retrieveX = module.getX;
+retrieveX();
+// returns 9 - The function gets invoked at the global scope
+
+// Create a new function with 'this' bound to module
+// New programmers might confuse the
+// global var x with module's property x
+var boundGetX = retrieveX.bind(module);
+boundGetX(); // 81
+
+ +

Partially applied functions

+ +

The next simplest use of bind() is to make a function with pre-specified initial arguments. These arguments (if any) follow the provided this value and are then inserted at the start of the arguments passed to the target function, followed by the arguments passed to the bound function, whenever the bound function is called.

+ +
function list() {
+  return Array.prototype.slice.call(arguments);
+}
+
+var list1 = list(1, 2, 3); // [1, 2, 3]
+
+// Create a function with a preset leading argument
+var leadingThirtysevenList = list.bind(null, 37);
+
+var list2 = leadingThirtysevenList();
+// [37]
+
+var list3 = leadingThirtysevenList(1, 2, 3);
+// [37, 1, 2, 3]
+
+ +

配合 setTimeout

+ +

By default within {{domxref("window.setTimeout()")}}, the this keyword will be set to the {{ domxref("window") }} (or global) object. When working with class methods that require this to refer to class instances, you may explicitly bind this to the callback function, in order to maintain the instance.

+ +
function LateBloomer() {
+  this.petalCount = Math.floor(Math.random() * 12) + 1;
+}
+
+// Declare bloom after a delay of 1 second
+LateBloomer.prototype.bloom = function() {
+  window.setTimeout(this.declare.bind(this), 1000);
+};
+
+LateBloomer.prototype.declare = function() {
+  console.log('I am a beautiful flower with ' +
+    this.petalCount + ' petals!');
+};
+
+var flower = new LateBloomer();
+flower.bloom();
+// after 1 second, triggers the 'declare' method
+ +

Bound functions used as constructors

+ +
+

Warning: This section demonstrates JavaScript capabilities and documents some edge cases of the bind() method. The methods shown below are not the best way to do things and probably should not be used in any production environment.

+
+ +

Bound functions are automatically suitable for use with the {{jsxref("Operators/new", "new")}} operator to construct new instances created by the target function. When a bound function is used to construct a value, the provided this is ignored. However, provided arguments are still prepended to the constructor call:

+ +
function Point(x, y) {
+  this.x = x;
+  this.y = y;
+}
+
+Point.prototype.toString = function() {
+  return this.x + ',' + this.y;
+};
+
+var p = new Point(1, 2);
+p.toString(); // '1,2'
+
+// not supported in the polyfill below,
+
+// works fine with native bind:
+
+var YAxisPoint = Point.bind(null, 0/*x*/);
+
+
+var emptyObj = {};
+var YAxisPoint = Point.bind(emptyObj, 0/*x*/);
+
+var axisPoint = new YAxisPoint(5);
+axisPoint.toString(); // '0,5'
+
+axisPoint instanceof Point; // true
+axisPoint instanceof YAxisPoint; // true
+new Point(17, 42) instanceof YAxisPoint; // true
+
+ +

Note that you need do nothing special to create a bound function for use with {{jsxref("Operators/new", "new")}}. The corollary is that you need do nothing special to create a bound function to be called plainly, even if you would rather require the bound function to only be called using {{jsxref("Operators/new", "new")}}.

+ +
// Example can be run directly in your JavaScript console
+// ...continuing from above
+
+// Can still be called as a normal function
+// (although usually this is undesired)
+YAxisPoint(13);
+
+emptyObj.x + ',' + emptyObj.y;
+// >  '0,13'
+
+ +

If you wish to support the use of a bound function only using {{jsxref("Operators/new", "new")}}, or only by calling it, the target function must enforce that restriction.

+ +

Creating shortcuts

+ +

bind() is also helpful in cases where you want to create a shortcut to a function which requires a specific this value.

+ +

Take {{jsxref("Array.prototype.slice")}}, for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this:

+ +
var slice = Array.prototype.slice;
+
+// ...
+
+slice.apply(arguments);
+
+ +

With bind(), this can be simplified. In the following piece of code, slice is a bound function to the {{jsxref("Function.prototype.apply()", "apply()")}} function of {{jsxref("Function.prototype")}}, with the this value set to the {{jsxref("Array.prototype.slice()", "slice()")}} function of {{jsxref("Array.prototype")}}. This means that additional apply() calls can be eliminated:

+ +
// same as "slice" in the previous example
+var unboundSlice = Array.prototype.slice;
+var slice = Function.prototype.apply.bind(unboundSlice);
+
+// ...
+
+slice(arguments);
+
+ +

Polyfill

+ +

You can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of bind() in implementations that do not natively support it.

+ +
if (!Function.prototype.bind) {
+  Function.prototype.bind = function(oThis) {
+    if (typeof this !== 'function') {
+      // closest thing possible to the ECMAScript 5
+      // internal IsCallable function
+      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
+    }
+
+    var aArgs   = Array.prototype.slice.call(arguments, 1),
+        fToBind = this,
+        fNOP    = function() {},
+        fBound  = function() {
+          return fToBind.apply(this instanceof fNOP
+                 ? this
+                 : oThis,
+                 aArgs.concat(Array.prototype.slice.call(arguments)));
+        };
+
+    if (this.prototype) {
+      // Function.prototype doesn't have a prototype property
+      fNOP.prototype = this.prototype;
+    }
+    fBound.prototype = new fNOP();
+
+    return fBound;
+  };
+}
+
+ +

Some of the many differences (there may well be others, as this list does not seriously attempt to be exhaustive) between this algorithm and the specified algorithm are:

+ + + +

If you choose to use this partial implementation, you must not rely on those cases where behavior deviates from ECMA-262, 5th edition! With some care, however (and perhaps with additional modification to suit specific needs), this partial implementation may be a reasonable bridge to the time when bind() is widely implemented according to the specification.

+ +

Please check https://github.com/Raynos/function-bind for a more thorough solution!

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.3.4.5', 'Function.prototype.bind')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES2015', '#sec-function.prototype.bind', 'Function.prototype.bind')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-function.prototype.bind', 'Function.prototype.bind')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("7")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2")}}{{CompatIE("9")}}{{CompatOpera("11.60")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatAndroid("4.0")}}{{CompatChrome("1")}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2")}}{{CompatUnknown}}{{CompatOperaMobile("11.5")}}{{CompatSafari("6.0")}}
+
+ +

相關連結

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/call/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/call/index.html new file mode 100644 index 0000000000..1d1d2017ee --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/call/index.html @@ -0,0 +1,105 @@ +--- +title: Function.prototype.call +slug: Web/JavaScript/Reference/Global_Objects/Function/call +translation_of: Web/JavaScript/Reference/Global_Objects/Function/call +--- +

{{JSRef}}

+ +

概述

+ +

使用給定的this參數以及分別給定的參數來呼叫某個函數

+ +
附註: 此函數的所有語法大致上與apply()相同,他們基本上不同處只有 call() 接受一連串的參數,而 apply() 單一的array作為參數
+ + + + + + + + + + + + + + + + + +
Function 物件的方法
被實作於JavaScript 1.3
ECMAScript 版本ECMAScript 第三版
+ +

語法

+ +
fun.call(thisArg[, arg1[, arg2[, ...]]])
+ +

參數

+ +
+
thisArg
+
呼叫fun時提供的this值。 注意,它可能是一個無法在函數內看到的值:若這個函數是在非嚴苛模式( non-strict mode ), null 、undefined 將會被置換成全域變數,而原生型態的值將會被封裝
+
arg1, arg2, ...
+
其他參數
+
+ +

描述

+ +

你可以在呼叫一個現存的函數時,使用不一樣的 this 物件。 this 會參照到目前的物件,呼叫的物件上

+ +

使用 call, 你可以實作函數一次,然後在其他的物件上直接繼承它,而不用在新的物件上重寫該函數

+ +

範例

+ +

使用 call 來串接物件上的建構子

+ +

你可以使用 call 來串接其他物件的建構子,就像 Java. 下面的例子中,Product 物件的建構子定義了兩個參數 name 以及 price. 其他函數FoodToy 引用了 Product 並傳入 thisnameprice。 Product 初始化它的屬性 nameprice, 而兩個子函數則定義了category。

+ +
function Product(name, price) {
+  this.name = name;
+  this.price = price;
+
+  if (price < 0)
+    throw RangeError('Cannot create product "' + name + '" with a negative price');
+  return this;
+}
+
+function Food(name, price) {
+  Product.call(this, name, price);
+  this.category = 'food';
+}
+Food.prototype = new Product();
+
+function Toy(name, price) {
+  Product.call(this, name, price);
+  this.category = 'toy';
+}
+Toy.prototype = new Product();
+
+var cheese = new Food('feta', 5);
+var fun = new Toy('robot', 40);
+
+ +

使用 call 來呼叫匿名的函數

+ +

下面這個簡易的例子中,我們做了一個匿名的函數,並用 call 來讓它應用在每個在串列中的物件中. 這個匿名函數的主要用途是加入一個print函數到每個物件上,這個函數可以印出每個物件的index指標。 傳入物件作為 this 的值並不是必要的,但他有解釋的用途。

+ +
var animals = [
+  {species: 'Lion', name: 'King'},
+  {species: 'Whale', name: 'Fail'}
+];
+
+for (var i = 0; i < animals.length; i++) {
+  (function (i) {
+    this.print = function () {
+      console.log('#' + i  + ' ' + this.species + ': ' + this.name);
+    }
+    this.print();
+  }).call(animals[i], i);
+}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..b88c087b24 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,191 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +tags: + - JavaScript + - JavaScript Reference + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

Function 建構函式可建立一個新的 Function 物件。在 JavaScript 中,所有的函式實際上都是 Function 物件。

+ +

語法

+ +
new Function ([arg1[, arg2[, ...argN]],] functionBody)
+ +

參數

+ +
+
arg1, arg2, ... argN
+
function 的引數名稱必須要符合正規的命名。每個名稱都必須要是有效的 JavaScript 識別符號規則的字串,或是使用英文逗號「, 」分隔開的字串清單; 像是 "x", "theValue", 或是 "a, b'。
+
functionBody
+
包含 JavaScript 狀態以及 function 定義的字串。
+
+ +

描述

+ +

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or function statement and calling it within your code, because such functions are parsed with the rest of the code.

+ +

All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.

+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Function 的屬性與方法

+ +

The global Function object has no methods or properties of its own, however, since it is a function itself it does inherit some methods and properties through the prototype chain from {{jsxref("Function.prototype")}}.

+ +

Function 原型物件

+ +

屬性 Properties

+ +
{{page('/zh-TW/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}
+ +

方法 Methods

+ +
{{page('/zh-TW/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}
+ +

Function 實例

+ +

Function instances inherit methods and properties from {{jsxref("Function.prototype")}}. As with all constructors, you can change the constructor's prototype object to make changes to all Function instances.

+ +

範例

+ +

Specifying arguments with the Function constructor

+ +

The following code creates a Function object that takes two arguments.

+ +
// Example can be run directly in your JavaScript console
+
+// Create a function that takes two arguments and returns the sum of those arguments
+var adder = new Function('a', 'b', 'return a + b');
+
+// Call the function
+adder(2, 6);
+// > 8
+
+ +

The arguments "a" and "b" are formal argument names that are used in the function body, "return a + b".

+ +

Difference between Function constructor and function declaration

+ +

Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.

+ +
var x = 10;
+
+function createFunction1() {
+    var x = 20;
+    return new Function('return x;'); // this |x| refers global |x|
+}
+
+function createFunction2() {
+    var x = 20;
+    function f() {
+        return x; // this |x| refers local |x| above
+    }
+    return f;
+}
+
+var f1 = createFunction1();
+console.log(f1());          // 10
+var f2 = createFunction2();
+console.log(f2());          // 20
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}{{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/global_objects/function/length/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/length/index.html new file mode 100644 index 0000000000..699e1ff178 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/length/index.html @@ -0,0 +1,144 @@ +--- +title: Function.length +slug: Web/JavaScript/Reference/Global_Objects/Function/length +translation_of: Web/JavaScript/Reference/Global_Objects/Function/length +--- +
{{JSRef}}
+ +

length property表示該 function 預期被傳入的參數數量

+ +
{{js_property_attributes(0,0,1)}}
+ +

描述

+ +

length 是 function 物件的一個 property,表示該 function 預期被傳入的參數數量,這個數量並不包含 {{jsxref("rest_parameters", "rest parameter", "", 1)}} 且只包涵第一個預設參數(Default Parameters)前的參數。相較之下 {{jsxref("Functions_and_function_scope/arguments/length", "arguments.length")}} 是 function 內部的物件,會提供真正傳進 function 中的參數數量。

+ +

Function 建構子的 data property

+ +

{{jsxref("Function")}} 建構子本身就是一個 {{jsxref("Function")}} 物件。其 length data property 的值為 1。此 property 的 attributes 包含: Writable: false, Enumerable: false, Configurable: true.

+ +

Function prototype 物件的 property

+ +

{{jsxref("Function")}} prototype 物件的 length property 其值為 0。

+ +

範例

+ +
console.log(Function.length); /* 1 */
+
+console.log((function()        {}).length); /* 0 */
+console.log((function(a)       {}).length); /* 1 */
+console.log((function(a, b)    {}).length); /* 2 以此類推. */
+
+console.log((function(...args) {}).length); /* 0, rest parameter 不包含在內 */
+
+console.log((function(a, b = 1, c) {}).length); /* 1 */
+// 只有在預設參數前的參數會被算到,也就是只有 a 會被視為必須傳入的參數
+// 而 c 將被預設為 undefined
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註釋
{{SpecName('ES1')}}{{Spec2('ES1')}}最初的定義,在 JavaScript 1.1 中實作。
{{SpecName('ES5.1', '#sec-15.3.5.1', 'Function.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ES6')}}此 property 的 configurable attribute 現在為 true.
{{SpecName('ESDraft', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
特點ChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatGeckoDesktop(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

可參閱

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/prototype/index.html new file mode 100644 index 0000000000..1db46bc59a --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/prototype/index.html @@ -0,0 +1,138 @@ +--- +title: Function.prototype +slug: Web/JavaScript/Reference/Global_Objects/Function/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

Function.prototype 屬性表示 {{jsxref("Function")}} 的原型物件。

+ +

描述

+ +

{{jsxref("Function")}} objects inherit from Function.prototypeFunction.prototype cannot be modified.

+ +

屬性

+ +
+
{{jsxref("Function.arguments")}} {{deprecated_inline}}
+
An array corresponding to the arguments passed to a function. This is deprecated as property of {{jsxref("Function")}}, use the {{jsxref("Functions/arguments", "arguments")}} object available within the function instead.
+
{{jsxref("Function.arity")}} {{obsolete_inline}}
+
Used to specifiy the number of arguments expected by the function, but has been removed. Use the {{jsxref("Function.length", "length")}} property instead.
+
{{jsxref("Function.caller")}} {{non-standard_inline}}
+
Specifies the function that invoked the currently executing function.
+
{{jsxref("Function.length")}}
+
Specifies the number of arguments expected by the function.
+
{{jsxref("Function.name")}}
+
The name of the function.
+
{{jsxref("Function.displayName")}} {{non-standard_inline}}
+
The display name of the function.
+
Function.prototype.constructor
+
Specifies the function that creates an object's prototype. See {{jsxref("Object.prototype.constructor")}} for more details.
+
+ +

方法

+ +
+
{{jsxref("Function.prototype.apply()")}}
+
Calls a function and sets its this to the provided value, arguments can be passed as an {{jsxref("Array")}} object.
+
{{jsxref("Function.prototype.bind()")}}
+
Creates a new function which, when called, has its this set to the provided value, with a given sequence of arguments preceding any provided when the new function was called.
+
{{jsxref("Function.prototype.call()")}}
+
Calls (executes) a function and sets its this to the provided value, arguments can be passed as they are.
+
{{jsxref("Function.prototype.isGenerator()")}} {{non-standard_inline}}
+
Returns true if the function is a generator; otherwise returns false.
+
{{jsxref("Function.prototype.toSource()")}} {{non-standard_inline}}
+
Returns a string representing the source code of the function. Overrides the {{jsxref("Object.prototype.toSource")}} method.
+
{{jsxref("Function.prototype.toString()")}}
+
Returns a string representing the source code of the function. Overrides the {{jsxref("Object.prototype.toString")}} method.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1
{{SpecName('ES5.1', '#sec-15.3.5.2', 'Function.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-instances-prototype', 'Function.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-instances-prototype', 'Function.prototype')}}{{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}}
+
+ +

參見

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