javascript学习笔记之Object类型测试

/* -------------------------
  Object 类型测试
  
  属性:
    constructor 创建对象的函数的引用
    prototype   对象原型对象引用
    
  方法:
    hasOwnProperty(property) 判断对象是否有某个非继承属性
    isPropertyOf(object) 判断该对象是否为传入对象的原型
    propertyIsEnumerable(property) 属性(非继承)是否可用for in 枚举
    toString() 返回对象字符串表示
    toLocaleString() 返回对象本地化字符串,Object默认的方法自身不做任何局部化,返回结果与toString()相同
    valueof() 返回最适合对象的原始值
    
----------------------------
*/

function writeline(message)
{
    document.write(message);
    document.write(
"<br>");
}


//Constructor
var ob = new Object();
writeline(ob.constructor 
== Object); //true
//
javascript为每一个定义的构造函数自动创建一个原型对象,所以默认的原型对象的constructor总是等于对象自身
function A(){};
writeline(A.prototype.constructor 
== A);//true
//
用constructor确定一个对象的类型
var a = new A();
if (typeof(a) == "object" && (a.constructor == A))
{
    writeline(
"a is A type"); //a is A type
}


//toString() 
//
当javascript需要将一个对象转换成字符串时调用该方法,如 "+"运算符,alert(),document.write()
//
默认的toString()提供的信息不多(object class形式),所以创建自定义类时最好自定义toString()方法返回有意义的信息
var ob2 = new Object();
writeline(ob2.toString()); 
//[object Object]

function Person(name,age)
{
    
this.getName = function(){ return name; };
    
this.getAge = function(){ return age; };
}
Person.prototype.toString 
= function()
{
    
return "name:" + this.getName() + ",age:" + this.getAge();
}

var aPerson = new Person("Jack",30);
writeline(aPerson); 
//name:Jack,age:30

//valueof() 
//
javascript 需要将一个对象转换成字符串之外的原始类型时,
//
需要调用它,这个函数返回是能代表关键字this所引用的对象的值的数据
//
由于大多数对象没有相对应的原始值,因此默认的Object类定义的valueof方法
//
不执行任何转换,只返回调用它的对象
var ob3 = new Object();
writeline(ob3.valueOf()); 
//[object Object]

//如果有对应原始值的对象,一般会重写valueof方法返回相应的原始值
var aNum = new Number(123);
var aStr = new String("abc");
writeline(aNum); 
//123 
writeline(aStr); //abc

//如果自定义类型有相应的原始值,建议实现valueof方法返回相应的原始值
function Complex(r,i)
{
    
this.real = r;
    
this.imaginary = i;
}

Complex.prototype.valueOf 
= function()
{
    
return this.real;
}

var c = new Complex(2,4);
writeline(c.valueOf()); 
//2

//hasOwnProperty 
var ob4 = new Object();
writeline(ob4.hasOwnProperty(
"undef")); //false, 未定义该属性

var a1 = new A();
a1.newProperty 
= "new";
writeline(a1.hasOwnProperty(
"newProperty")); //true
writeline(a1.hasOwnProperty("constructor")); //false 继承属性

//propertyIsEnumaerable
//
var ob5 =

    x:
567,
    
1:1
};
writeline(ob5.propertyIsEnumerable(
"x")); //true
writeline(ob5.propertyIsEnumerable(1)); //true
for(var prop in ob5)
{
    writeline(ob5[prop]);
//567,1
}

//isPrototypeOf 与constructor用法相似,
//
constructor是从对象自身检查是否为某类型的对象
//
isPrototypeOf是检查一个对象否为另一个对象的原型
var ob6 = new Object();
writeline(Object.prototype.isPrototypeOf(ob6));
//true ob6.constructor == Object
writeline(Object.isPrototypeOf(ob6)); //false
writeline(Function.prototype.isPrototypeOf(Object));//true Object.constructor == Function

posted @ 2009-04-06 00:45  十三  阅读(1844)  评论(0编辑  收藏  举报