4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>The source code</title>
6 <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
7 <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
8 <style type="text/css">
9 .highlight { display: block; background-color: #ddd; }
11 <script type="text/javascript">
12 function highlight() {
13 document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
17 <body onload="prettyPrint(); highlight();">
18 <pre class="prettyprint lang-js"><span id='Function'>/**
19 </span> * @class Function
21 * Every function in JavaScript is actually a `Function` object.
23 * `Function` objects created with the `Function` constructor are parsed when the
24 * function is created. This is less efficient than declaring a function and
25 * calling it within your code, because functions declared with the function
26 * statement are parsed with the rest of the code.
28 * All arguments passed to the function are treated as the names of the
29 * identifiers of the parameters in the function to be created, in the order in
30 * which they are passed.
32 * Invoking the `Function` constructor as a function (without using the `new`
33 * operator) has the same effect as invoking it as a constructor.
35 * # Specifying arguments with the `Function` constructor
37 * The following code creates a `Function` object that takes two arguments.
39 * // Example can be run directly in your JavaScript console
41 * // Create a function that takes two arguments and returns the sum of those
43 * var adder = new Function("a", "b", "return a + b");
45 * // Call the function
49 * The arguments "a" and "b" are formal argument names that are used in the
50 * function body, "return a + b".
52 * <div class="notice">
53 * Documentation for this class comes from <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">MDN</a>
54 * and is available under <a href="http://creativecommons.org/licenses/by-sa/2.0/">Creative Commons: Attribution-Sharealike license</a>.
58 <span id='Function-method-constructor'>/**
59 </span> * @method constructor
60 * Creates new Function object.
62 * @param {String...} args
63 * Names to be used by the function as formal argument names. Each must be a
64 * string that corresponds to a valid JavaScript identifier or a list of such
65 * strings separated with a comma; for example "`x`", "`theValue`", or "`a,b`".
66 * @param {String} functionBody
67 * A string containing the JavaScript statements comprising the function
73 <span id='Function-property-length'>/**
74 </span> * @property {Number} length
75 * Specifies the number of arguments expected by the function.
80 <span id='Function-method-apply'>/**
81 </span> * @method apply
82 * Applies the method of another object in the context of a different object (the
83 * calling object); arguments can be passed as an Array object.
85 * You can assign a different this object when calling an existing function. `this` refers to the
86 * current object, the calling object. With `apply`, you can write a method once and then inherit it
87 * in another object, without having to rewrite the method for the new object.
89 * `apply` is very similar to call, except for the type of arguments it supports. You can use an
90 * arguments array instead of a named set of parameters. With apply, you can use an array literal, for
91 * example, `fun.apply(this, ['eat', 'bananas'])`, or an Array object, for example, `fun.apply(this,
92 * new Array('eat', 'bananas'))`.
94 * You can also use arguments for the `argsArray` parameter. `arguments` is a local variable of a
95 * function. It can be used for all unspecified arguments of the called object. Thus, you do not have
96 * to know the arguments of the called object when you use the `apply` method. You can use arguments
97 * to pass all the arguments to the called object. The called object is then responsible for handling
100 * Since ECMAScript 5th Edition you can also use any kind of object which is array like, so in
101 * practice this means it's going to have a property length and integer properties in the range
102 * `[0...length)`. As an example you can now use a NodeList or a own custom object like `{'length': 2,
103 * '0': 'eat', '1': 'bananas'}`.
105 * You can use `apply` to chain constructors for an object, similar to Java. In the following example,
106 * the constructor for the `Product` object is defined with two parameters, `name` and `value`. Two
107 * other functions `Food` and `Toy` invoke `Product` passing `this` and `arguments`. `Product`
108 * initializes the properties `name` and `price`, both specialized functions define the category. In
109 * this example, the `arguments` object is fully passed to the product constructor and corresponds to
110 * the two defined parameters.
112 * function Product(name, price) {
114 * this.price = price;
117 * throw RangeError('Cannot create product "' + name + '" with a negative price');
121 * function Food(name, price) {
122 * Product.apply(this, arguments);
123 * this.category = 'food';
125 * Food.prototype = new Product();
127 * function Toy(name, price) {
128 * Product.apply(this, arguments);
129 * this.category = 'toy';
131 * Toy.prototype = new Product();
133 * var cheese = new Food('feta', 5);
134 * var fun = new Toy('robot', 40);
136 * Clever usage of `apply` allows you to use built-ins functions for some tasks that otherwise
137 * probably would have been written by looping over the array values. As an example here we are going
138 * to use Math.max/Math.min to find out the maximum/minimum value in an array.
140 * //min/max number in an array
141 * var numbers = [5, 6, 2, 3, 7];
143 * //using Math.min/Math.max apply
144 * var max = Math.max.apply(null, numbers); // This about equal to Math.max(numbers[0], ...) or
145 * // Math.max(5, 6, ..)
146 * var min = Math.min.apply(null, numbers);
148 * //vs. simple loop based algorithm
149 * max = -Infinity, min = +Infinity;
151 * for (var i = 0; i < numbers.length; i++) {
152 * if (numbers[i] > max)
154 * if (numbers[i] < min)
158 * But beware: in using `apply` this way, you run the risk of exceeding the JavaScript engine's
159 * argument length limit. The consequences of applying a function with too many arguments (think more
160 * than tens of thousands of arguments) vary across engines, because the limit (indeed even the nature
161 * of any excessively-large-stack behavior) is unspecified. Some engines will throw an exception. More
162 * perniciously, others will arbitrarily limit the number of arguments actually passed to the applied
163 * function. (To illustrate this latter case: if such an engine had a limit of four arguments [actual
164 * limits are of course significantly higher], it would be as if the arguments 5, 6, 2, 3 had been
165 * passed to apply in the examples above, rather than the full array.) If your value array might grow
166 * into the tens of thousands, use a hybrid strategy: apply your function to chunks of the array at a
169 * function minOfArray(arr)
171 * var min = Infinity;
172 * var QUANTUM = 32768;
173 * for (var i = 0, len = arr.length; i < len; i += QUANTUM)
175 * var submin = Math.min.apply(null, numbers.slice(i, Math.min(i + QUANTUM, len)));
176 * min = Math.min(submin, min);
181 * var min = minOfArray([5, 6, 2, 3, 7]);
183 * @param {Object} thisArg The value of this provided for the call to fun. Note that this may not be
184 * the actual value seen by the method: if the method is a function in non-strict mode code, null and
185 * undefined will be replaced with the global object, and primitive values will be boxed.
186 * @param {Array} argsArray An array like object, specifying the arguments with which fun should be
187 * called, or null or undefined if no arguments should be provided to the function.
188 * @return {Object} Returns what the function returns.
191 <span id='Function-method-call'>/**
192 </span> * @method call
193 * Calls (executes) a method of another object in the context of a different
194 * object (the calling object); arguments can be passed as they are.
196 * You can assign a different this object when calling an existing function. `this` refers to the
197 * current object, the calling object.
199 * With `call`, you can write a method once and then inherit it in another object, without having to
200 * rewrite the method for the new object.
202 * You can use call to chain constructors for an object, similar to Java. In the following example,
203 * the constructor for the product object is defined with two parameters, name and value. Another
204 * object, `prod_dept`, initializes its unique variable (`dept`) and calls the constructor for
205 * `product` in its constructor to initialize the other variables.
207 * function Product(name, price) {
209 * this.price = price;
212 * throw RangeError('Cannot create product "' + name + '" with a negative price');
216 * function Food(name, price) {
217 * Product.call(this, name, price);
218 * this.category = 'food';
220 * Food.prototype = new Product();
222 * function Toy(name, price) {
223 * Product.call(this, name, price);
224 * this.category = 'toy';
226 * Toy.prototype = new Product();
228 * var cheese = new Food('feta', 5);
229 * var fun = new Toy('robot', 40);
231 * In this purely constructed example, we create anonymous function and use `call` to invoke it on
232 * every object in an array. The main purpose of the anonymous function here is to add a print
233 * function to every object, which is able to print the right index of the object in the array.
234 * Passing the object as `this` value was not strictly necessary, but is done for explanatory purpose.
237 * {species: 'Lion', name: 'King'},
238 * {species: 'Whale', name: 'Fail'}
241 * for (var i = 0; i < animals.length; i++) {
243 * this.print = function () {
244 * console.log('#' + i + ' ' + this.species + ': ' + this.name);
246 * }).call(animals[i], i);
249 * @param {Object} thisArg The value of this provided for the call to `fun`.Note that this may not be
250 * the actual value seen by the method: if the method is a function in non-strict mode code, `null`
251 * and `undefined` will be replaced with the global object, and primitive values will be boxed.
252 * @param {Object...} args Arguments for the object.
253 * @return {Object} Returns what the function returns.
256 <span id='Function-method-toString'>/**
257 </span> * @method toString
258 * Returns a string representing the source code of the function. Overrides the
259 * `Object.toString` method.
261 * The {@link Function} object overrides the `toString` method of the Object object; it does
262 * not inherit Object.toString. For `Function` objects, the `toString` method returns a string
263 * representation of the object.
265 * JavaScript calls the `toString` method automatically when a `Function` is to be represented as a
266 * text value or when a Function is referred to in a string concatenation.
268 * For `Function` objects, the built-in `toString` method decompiles the function back into the
269 * JavaScript source that defines the function. This string includes the `function` keyword, the
270 * argument list, curly braces, and function body.
272 * @return {String} The function as a string.