- function Person (){}; var p = new Person();
对应的构造函数
- Object.prototype
- var o = {
- appendTo: function(dom) {}
- };
- function DivTag() {}
- DivTag.prototype = o;
- var div = new DivTag();
在 js 中 使用 Function 可以实例化函数对象. 也就是说在 js 中函数与普通对象一样, 也是一个对象类型 (非常特殊)
- new Function(arg0, arg1, arg2, ..., argN, body);
- // 传统的
- function foo() {
- console.log('你好');
- }
- // Function
- var func = new Function('console.log( "你好" );');
- // 功能上, 这里 foo 与 func 等价
- // 传统
- function foo() {}
- // Function
- var func = new Function();
- // 传统
- function foo(num) {
- console.log(num);
- }
- // Function
- var func = new Function("num", "console.log( num );");
- func();
- var func = new Function('num1', 'num2', 'console.log( num1 + num2 );');
练习: 利用 Function 创建一个函数, 要求允许函数调用时传入任意个数参数, 并且函数返回这些数字中最大的数字.
练习: 利用 Function 创建一个求三个数中最大数的函数.
- // 传统
- function foo(a, b, c) {
- var res = a > b ? a: b;
- res = res > c ? res: c;
- return res;
- }
- // Function
- var func = new Function('a', 'b', 'c', 'var res = a > b ? a : b;res = res > c ? res : c;return res;')
解决代码太长的办法:
- var func = new Function('a', 'b', 'c', 'var res = a > b ? a : b;' + 'res = res > c ? res : c;' + 'return res;');
- function foo(a, b, c) {
- var res = a > b ? a: b;
- res = res > c ? res: c;
- return res;
- }
- var func = new Function('a', 'b', 'c', 'return foo( a, b, c );');
arguments 是一个伪数组对象. 它表示在函数调用的过程中传入的所有参数的集合.
在函数调用过程中没有规定参数的个数与类型, 因此函数调用就具有灵活的特性, 那么为了方便使用,
在 每一个函数调用的过程中, 函数代码体内有一个默认的对象 arguments, 它存储着实际传入的所有参数.
js 中函数并没有规定必须如何传参
在代码设计中, 如果需要函数带有任意个参数的时候, 一般就不带任何参数, 所有的 参数利用 arguments 来获取.
一般的函数定义语法, 可以写成:
- function foo(
- /* ... */
- ) {}
- function foo() {
- // 所有的参数都在 arguments 中. 将其当做数组使用
- // 问题而已转换成在有一个数组中求最大值
- var args = arguments;
- var max = args[0];
- for (var i = 1; i < args.length; i++) {
- if (max < args[i]) {
- max = args[i];
- }
- }
- return max;
- }
练习: 利用 Function 写一个函数, 要求传入任意个数字 求和
任意的一个函数, 都是相当于 Function 的实例. 类似于 {} 与 new Object() 的关系
- function foo() {};
- // 告诉解释器, 有一个对象叫 foo, 它是一个函数
- // 相当于 new Function() 得到一个 函数对象
属性
- __proto__
- Function.prototype
继承自
- Fucntion.prototype
- Object.protoype
判断 构造函数 Array 的原型 是否在 实例对象 array 的原型链存在
- array instanceof Array
来源: http://www.cnblogs.com/liu666/p/5845005.html