“一切都是对象” 这句话的重点在于如何去理解“对象”这个概念。 当然 , 也不是所有的都是对象,值类型就不是对象。
先看看js中一个常用的函数 typeof()。 typeof()函数输出的类型如下:
<script>
function showType(){
document.writeln(typeof(10)); // number
document.writeln("<br/>");
document.writeln(typeof(a)); // undefined
document.writeln("<br/>");
var b;
document.writeln(typeof(b)); // undefined
document.writeln("<br/>");
document.writeln(typeof("string")); // string
document.writeln("<br/>");
document.writeln(typeof(false)); // boolean
document.writeln("<br/>");
document.writeln(typeof(function(){alert('8888');})); // function
document.writeln("<br/>");
document.writeln(typeof({a:'34',b:'4444',c:45555})); // object
document.writeln("<br/>");
document.writeln(typeof([1,2,3,4,true,'string'])); // object
document.writeln("<br/>");
document.writeln(typeof(null)); // object
document.writeln("<br/>");
document.writeln(typeof(new Number(23))); // object
document.writeln("<br/>");
}
showType();
</script>
以上代码列出了typeof() 函数输出的几种数据类型。其中(number,undefined,string,boolean)属于简单的值类型,不是对象, 其中(函数,数组,对象,null,new Number(10))都是对象,都是引用类型。
判断一个变量是否是对象非常简单,值类型的类型判断可以通过typeof ,引用类型的类型判断可以使用 instanceof :
var array =new Array();
if(array instanceof Object){
alert('shi');
}
对象 - 若干属性的集合 java或者C# 中的对象都是通过一个类new 出来的。而且里面有字段,属性,方法,规定的非常严格。但是js就比较随意了 - - ,数组是对象,函数是对象,对象还是对象,对象里面的一切都是属性,只有属性,没有方法。那么这样方法如何表示呢? - - 方法也是一种属性,并以键值对的形式表示。在js中对象可以任意的扩展属性,没有class的约束。
常见的例子:
var obj = {
a:10,
b:function(x){
alert(x+this.a);
},
c:{
name:'wangxiaobo',
year:1990
}
};
以上代码中,obj是一个自定义的对象,其中a,b,c就是它的属性,而且c的属性值还是一个对象,它又有name,year两个属性。
这个可能比较好理解,那么函数和数组也可以这样定义吗?- - 当然不行,但是它们可以用另外一种形式,总之函数/数组之流,只要是对象,它就是属性的集合。 以函数为例子:
var fn = function(){
alert('hello wangxiaobo');
};
fn.a = 12;
fn.b = function(){
alert(333);
};
fn.c={
name:'wangming',
age:33
};
上段代码中,函数就作为对象被赋值了a,b,三个属性 ,可见对象就是属性的集合。
上面的书写形式还是有用的。 在jquery 源码中,‘jquery’或者 ‘$’,这个变量其实是一个函数,
console.log(typeof ($)); // function
console.log($.trim(" ABC "));
$.trim() 也是一个函数,很明显,这就是在$或者Jquery函数上加上一个trim()属性,属性值是一个函数,作用是截取字符串的前后空格。
最后有个疑问,在typeof的输出类型中,function和object都是对象,为何却要输出两种呢?都输出object不行吗?