Function.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  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; }
  10. </style>
  11. <script type="text/javascript">
  12. function highlight() {
  13. document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
  14. }
  15. </script>
  16. </head>
  17. <body onload="prettyPrint(); highlight();">
  18. <pre class="prettyprint lang-js"><span id='Function'>/**
  19. </span> * @class Function
  20. *
  21. * Every function in JavaScript is actually a `Function` object.
  22. *
  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.
  27. *
  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.
  31. *
  32. * Invoking the `Function` constructor as a function (without using the `new`
  33. * operator) has the same effect as invoking it as a constructor.
  34. *
  35. * # Specifying arguments with the `Function` constructor
  36. *
  37. * The following code creates a `Function` object that takes two arguments.
  38. *
  39. * // Example can be run directly in your JavaScript console
  40. *
  41. * // Create a function that takes two arguments and returns the sum of those
  42. * arguments
  43. * var adder = new Function(&quot;a&quot;, &quot;b&quot;, &quot;return a + b&quot;);
  44. *
  45. * // Call the function
  46. * adder(2, 6);
  47. * // &gt; 8
  48. *
  49. * The arguments &quot;a&quot; and &quot;b&quot; are formal argument names that are used in the
  50. * function body, &quot;return a + b&quot;.
  51. *
  52. * &lt;div class=&quot;notice&quot;&gt;
  53. * Documentation for this class comes from &lt;a href=&quot;https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function&quot;&gt;MDN&lt;/a&gt;
  54. * and is available under &lt;a href=&quot;http://creativecommons.org/licenses/by-sa/2.0/&quot;&gt;Creative Commons: Attribution-Sharealike license&lt;/a&gt;.
  55. * &lt;/div&gt;
  56. */
  57. <span id='Function-method-constructor'>/**
  58. </span> * @method constructor
  59. * Creates new Function object.
  60. *
  61. * @param {String...} args
  62. * Names to be used by the function as formal argument names. Each must be a
  63. * string that corresponds to a valid JavaScript identifier or a list of such
  64. * strings separated with a comma; for example &quot;`x`&quot;, &quot;`theValue`&quot;, or &quot;`a,b`&quot;.
  65. * @param {String} functionBody
  66. * A string containing the JavaScript statements comprising the function
  67. * definition.
  68. */
  69. // Properties
  70. <span id='Function-property-length'>/**
  71. </span> * @property {Number} length
  72. * Specifies the number of arguments expected by the function.
  73. */
  74. //Methods
  75. <span id='Function-method-apply'>/**
  76. </span> * @method apply
  77. * Applies the method of another object in the context of a different object (the
  78. * calling object); arguments can be passed as an Array object.
  79. *
  80. * You can assign a different this object when calling an existing function. `this` refers to the
  81. * current object, the calling object. With `apply`, you can write a method once and then inherit it
  82. * in another object, without having to rewrite the method for the new object.
  83. *
  84. * `apply` is very similar to call, except for the type of arguments it supports. You can use an
  85. * arguments array instead of a named set of parameters. With apply, you can use an array literal, for
  86. * example, `fun.apply(this, ['eat', 'bananas'])`, or an Array object, for example, `fun.apply(this,
  87. * new Array('eat', 'bananas'))`.
  88. *
  89. * You can also use arguments for the `argsArray` parameter. `arguments` is a local variable of a
  90. * function. It can be used for all unspecified arguments of the called object. Thus, you do not have
  91. * to know the arguments of the called object when you use the `apply` method. You can use arguments
  92. * to pass all the arguments to the called object. The called object is then responsible for handling
  93. * the arguments.
  94. *
  95. * Since ECMAScript 5th Edition you can also use any kind of object which is array like, so in
  96. * practice this means it's going to have a property length and integer properties in the range
  97. * `[0...length)`. As an example you can now use a NodeList or a own custom object like `{'length': 2,
  98. * '0': 'eat', '1': 'bananas'}`.
  99. *
  100. * You can use `apply` to chain constructors for an object, similar to Java. In the following example,
  101. * the constructor for the `Product` object is defined with two parameters, `name` and `value`. Two
  102. * other functions `Food` and `Toy` invoke `Product` passing `this` and `arguments`. `Product`
  103. * initializes the properties `name` and `price`, both specialized functions define the category. In
  104. * this example, the `arguments` object is fully passed to the product constructor and corresponds to
  105. * the two defined parameters.
  106. *
  107. * function Product(name, price) {
  108. * this.name = name;
  109. * this.price = price;
  110. *
  111. * if (price &lt; 0)
  112. * throw RangeError('Cannot create product &quot;' + name + '&quot; with a negative price');
  113. * return this;
  114. * }
  115. *
  116. * function Food(name, price) {
  117. * Product.apply(this, arguments);
  118. * this.category = 'food';
  119. * }
  120. * Food.prototype = new Product();
  121. *
  122. * function Toy(name, price) {
  123. * Product.apply(this, arguments);
  124. * this.category = 'toy';
  125. * }
  126. * Toy.prototype = new Product();
  127. *
  128. * var cheese = new Food('feta', 5);
  129. * var fun = new Toy('robot', 40);
  130. *
  131. * Clever usage of `apply` allows you to use built-ins functions for some tasks that otherwise
  132. * probably would have been written by looping over the array values. As an example here we are going
  133. * to use Math.max/Math.min to find out the maximum/minimum value in an array.
  134. *
  135. * //min/max number in an array
  136. * var numbers = [5, 6, 2, 3, 7];
  137. *
  138. * //using Math.min/Math.max apply
  139. * var max = Math.max.apply(null, numbers); // This about equal to Math.max(numbers[0], ...) or
  140. * // Math.max(5, 6, ..)
  141. * var min = Math.min.apply(null, numbers);
  142. *
  143. * //vs. simple loop based algorithm
  144. * max = -Infinity, min = +Infinity;
  145. *
  146. * for (var i = 0; i &lt; numbers.length; i++) {
  147. * if (numbers[i] &gt; max)
  148. * max = numbers[i];
  149. * if (numbers[i] &lt; min)
  150. * min = numbers[i];
  151. * }
  152. *
  153. * But beware: in using `apply` this way, you run the risk of exceeding the JavaScript engine's
  154. * argument length limit. The consequences of applying a function with too many arguments (think more
  155. * than tens of thousands of arguments) vary across engines, because the limit (indeed even the nature
  156. * of any excessively-large-stack behavior) is unspecified. Some engines will throw an exception. More
  157. * perniciously, others will arbitrarily limit the number of arguments actually passed to the applied
  158. * function. (To illustrate this latter case: if such an engine had a limit of four arguments [actual
  159. * limits are of course significantly higher], it would be as if the arguments 5, 6, 2, 3 had been
  160. * passed to apply in the examples above, rather than the full array.) If your value array might grow
  161. * into the tens of thousands, use a hybrid strategy: apply your function to chunks of the array at a
  162. * time:
  163. *
  164. * function minOfArray(arr)
  165. * {
  166. * var min = Infinity;
  167. * var QUANTUM = 32768;
  168. * for (var i = 0, len = arr.length; i &lt; len; i += QUANTUM)
  169. * {
  170. * var submin = Math.min.apply(null, numbers.slice(i, Math.min(i + QUANTUM, len)));
  171. * min = Math.min(submin, min);
  172. * }
  173. * return min;
  174. * }
  175. *
  176. * var min = minOfArray([5, 6, 2, 3, 7]);
  177. *
  178. * @param {Object} thisArg The value of this provided for the call to fun. Note that this may not be
  179. * the actual value seen by the method: if the method is a function in non-strict mode code, null and
  180. * undefined will be replaced with the global object, and primitive values will be boxed.
  181. * @param {Array} argsArray An array like object, specifying the arguments with which fun should be
  182. * called, or null or undefined if no arguments should be provided to the function.
  183. * @return {Object} Returns what the function returns.
  184. */
  185. <span id='Function-method-call'>/**
  186. </span> * @method call
  187. * Calls (executes) a method of another object in the context of a different
  188. * object (the calling object); arguments can be passed as they are.
  189. *
  190. * You can assign a different this object when calling an existing function. `this` refers to the
  191. * current object, the calling object.
  192. *
  193. * With `call`, you can write a method once and then inherit it in another object, without having to
  194. * rewrite the method for the new object.
  195. *
  196. * You can use call to chain constructors for an object, similar to Java. In the following example,
  197. * the constructor for the product object is defined with two parameters, name and value. Another
  198. * object, `prod_dept`, initializes its unique variable (`dept`) and calls the constructor for
  199. * `product` in its constructor to initialize the other variables.
  200. *
  201. * function Product(name, price) {
  202. * this.name = name;
  203. * this.price = price;
  204. *
  205. * if (price &lt; 0)
  206. * throw RangeError('Cannot create product &quot;' + name + '&quot; with a negative price');
  207. * return this;
  208. * }
  209. *
  210. * function Food(name, price) {
  211. * Product.call(this, name, price);
  212. * this.category = 'food';
  213. * }
  214. * Food.prototype = new Product();
  215. *
  216. * function Toy(name, price) {
  217. * Product.call(this, name, price);
  218. * this.category = 'toy';
  219. * }
  220. * Toy.prototype = new Product();
  221. *
  222. * var cheese = new Food('feta', 5);
  223. * var fun = new Toy('robot', 40);
  224. *
  225. * In this purely constructed example, we create anonymous function and use `call` to invoke it on
  226. * every object in an array. The main purpose of the anonymous function here is to add a print
  227. * function to every object, which is able to print the right index of the object in the array.
  228. * Passing the object as `this` value was not strictly necessary, but is done for explanatory purpose.
  229. *
  230. * var animals = [
  231. * {species: 'Lion', name: 'King'},
  232. * {species: 'Whale', name: 'Fail'}
  233. * ];
  234. *
  235. * for (var i = 0; i &lt; animals.length; i++) {
  236. * (function (i) {
  237. * this.print = function () {
  238. * console.log('#' + i + ' ' + this.species + ': ' + this.name);
  239. * }
  240. * }).call(animals[i], i);
  241. * }
  242. *
  243. * @param {Object} thisArg The value of this provided for the call to `fun`.Note that this may not be
  244. * the actual value seen by the method: if the method is a function in non-strict mode code, `null`
  245. * and `undefined` will be replaced with the global object, and primitive values will be boxed.
  246. * @param {Object...} args Arguments for the object.
  247. * @return {Object} Returns what the function returns.
  248. */
  249. <span id='Function-method-toString'>/**
  250. </span> * @method toString
  251. * Returns a string representing the source code of the function. Overrides the
  252. * `Object.toString` method.
  253. *
  254. * The {@link Function} object overrides the `toString` method of the Object object; it does
  255. * not inherit Object.toString. For `Function` objects, the `toString` method returns a string
  256. * representation of the object.
  257. *
  258. * JavaScript calls the `toString` method automatically when a `Function` is to be represented as a
  259. * text value or when a Function is referred to in a string concatenation.
  260. *
  261. * For `Function` objects, the built-in `toString` method decompiles the function back into the
  262. * JavaScript source that defines the function. This string includes the `function` keyword, the
  263. * argument list, curly braces, and function body.
  264. *
  265. * @return {String} The function as a string.
  266. */</pre>
  267. </body>
  268. </html>