上文已经提到,函数是对象的一种,因为可以通过instanceof判断。
1 var fn = function () { }; 2 console.log(fn instanceof Object); // true
函数是一种对象,但函数不像数组那样——你可以说数组是对象的一种,因为数组就像对象的一个子集一样。但函数与对象之间却不仅仅是包含与被包含的关系。
先看一个小例子
1 function Fn() { 2 this.name = '王福朋'; 3 this.year = 1988; 4 } 5 var fn1 = new Fn();
上面的例子说明:对象可以通过函数来创建
1 //var obj = { a: 10, b: 20 }; 2 //var arr = [5, 'x', true]; 3 4 var obj = new Object(); 5 obj.a = 10; 6 obj.b = 20; 7 8 var arr = new Array(); 9 arr[0] = 5; 10 arr[1] = 'x'; 11 arr[2] = true;
而其中的 Object 和 Array 都是函数:
1 console.log(typeof (Object)); // function 2 console.log(typeof (Array)); // function
对象是函数创建得,而函数本身又是一种对象。那对象和函数到底是什么关系呢,这就要说prototype原型了。