1、对象内置属性
几乎所有的对象都是同源对象,它们都继承自Object对象,都拥有父类的属性和方法。这些属性和方法主要包括。
(1)、属性:constructor,任何一个对象实例的该属性总是对构造函数即对象类本身的引用,从概念上说,它就是对象实例所属的对象类,它总是指向当前类本身,因此常用它来
进行准确的运行时类型识别。该属性类似于java中的对象的class属性,为对象本身提供了极其重要的元数据——类型本身。
//使用constructor判断变量类型
var num = 10;
if (num.constructor =Number) {
alert("num是数字类型!");
}
//打印function
alert(typeof(num.constructor));
(2)、属性:proptoty,对象类型原型的引用。
function test(name) {
this.name = name;
}
//通过prototype为对象的实例添加属性
test.prototype.age = "100";
alert(test.age);//undefined
alert((new test("张三")).age);
//注意使用下面的方式添加的属性是为类添加属性,没有创建对象就可以访问,而使用prototype添加的属性必须创建对象才能访问
test.sex = "男";
alert(test.sex);//男
//注意函数才有prototype属性,使用new创建的对象没有该属性
alert(test.prototype);//Object
alert((new test("张三")).prototype);//undefined
(3)、方法:hasOwnProperty(),用来检查对象是否拥有局部定义的(非继承的)、具有特定名字的属性。
var obj = new Object();
//打印false
alert(obj.hasOwnProperty("name"));
obj.name = "未知";
//打印true
alert(obj.hasOwnProperty("name"));
(4)、方法:isPrototypeOf(),检查对象是否是指定对象的原型。
function test1() {
}
function test2() {
}
//打印true
alert(test1.prototype.isPrototypeOf(new test1()));
//打印false
alert(test2.prototype.isPrototypeOf(new test1()));
(5)、方法:propertyIsEmuerable(),检查对象是否拥有指定属性且这个属性可以被for……in循环枚举。只有当对象拥有某个属性并且该属性可被枚举时,该方法返回true,属性是否可以枚举是由
Javascript内部机制决定的,一般情况用户自定义的对象属性都是可枚举的。
function test(name) {
this.name = name;
}
var obj = new test("张三");
alert(obj.propertyIsEnumerable("name"));
//下面循环执行一次,打印name
for (var o in obj) {
alert(o);
}
(6)、方法:toLocaleString()返回对象本地化的字符串表示,该方法的默认实现是调用toString()方法,但子类可以覆盖它,提供本地化。
1283

被折叠的 条评论
为什么被折叠?



