一、ToString()
- 返回对象的字符串表示
- 返回的字符串可能是具体的值,也可能是类型标识[object class]
- 示例
function F(x,y){
this.x=x;
this.y=y
}
var f=new F(1,2);
alert(F.toString());
alert(f.toString());
//重写toString,让实例对象可以返回构造函数的源代码
Object.prototype.toString=function(){
return this.constructor.toString();
}
alert(f.toString());
运行结果:
- toLocaleString()方法能返回对象的本地字符串表示。Object对象定义toLocaleString()方法默认返回值与toString()方法返回值完全相同。
- toString()函数可以用来判断对象数据类型,弥补typeof运算符和constructor属性在这方面的不足
二、valueOf()
- valueOf()方法返回对象的值
- Object对象默认valueOf()方法与toSring()方法返回值相同,但是部分类型对象重写了valueOf方法。
Date对象的valueOf()方法返回的是当前日期对象的毫秒数
var o =new Date();
alert(o.toString()); //返回当前时间的utc字符串
alert(o.valueOf()); //返回当前时间距离1970年1月1日的毫秒数
alert(Object.prototype.valueOf.apply(o)); //返回当前时间的utc字符串
- 在特定环境下数据类型转换时(如把对象转换字符串),valueOf()方法的优先级要比toString()方法的优先级高。
function Point(x,y){
this.x=x;
this.y=y;
}
Point.prototype.valueOf=function(){
return "("+this.x+","+this.y+")"
}
Point.prototype.toString=function(){
return "[object Point]"
}
var p=new Point(26,68);
alert("typeof p =" + p); //默认调用valueOf()方法进行类型转化
alert("typeof p =" + p.toString());
三、hasOwnProperty()
1.对象属性分为:继承属性、私有属性
2.hasOwnProperty()方法的作用:判断属性的类型
function F(){
F.name="私有属性";
}
F.prototype.name="继承属性";
var f=new F();
document.write(f.hasOwnProperty("name"));//返回false
document.write(f.name);//返回继承属性
3.hasOwnProperty()方法只能判断出对象中是否包含指定名称的属性,但无法检查对象原型链中是否包含某个属性,所以能够检测出来的属性必须是对象成员。
四、propertyIsEnumerable()
1.作用:判定指定本地属性是否允许枚举,如果方法返回值为true,则说明指定的本地属性可以枚举,否则不允许枚举。
function F(){
this.a=1;
this.b=2;
}
F.prototype.c=3;
F.d=4;
var f=new F();
f.e=5;
for(var I in f){
document.write(I+"<br/>");
}
alert(f.propertyIsEnumerable("a"));
alert(f.propertyIsEnumerable("b"));
alert(f.propertyIsEnumerable("c"));
alert(f.propertyIsEnumerable("d"));
alert(f.propertyIsEnumerable("e"));
五、isPrototypeOf()
1.在JavaScript中,Function对象预定义了prototype属性,该属性指向一个原型对象。
2.当定义构造函数时,系统会自动创建一个对象,即原型对象,并传递prototype属性。
3.原型对象可以存储构造类型的原型属性
4.isPrototypeOf()方法可以检测一个对象是否为另一个对象的原型对象
var f=function(){};
f.prototype={
a:1,
b:function(){
return 2;
}
}
document.write(f.prototype.a);
document.write(f.prototype.b());
var o=new f();
var b=f.prototype.isPrototypeOf(o);
document.write("<br/>"+b);
六、静态方法
1.静态方法由构造函数直接定义,动态方法是在构造函数的原型上定义
2.静态方法可由构造函数直接调用,而动态方法必须由实例化对象调用