每个对象都含有以下属性方法
- ? constructor — The function that was used to create the object.
- ? hasOwnProperty(propertyName) — Indicates if the given property exists on the object instance (not on the prototype). The property name must be specified as a string (for example, o.hasOwnProperty(“name”)).
- ? isPrototypeOf(object) — Determines if the object is a prototype of another object.
- ? propertyIsEnumerable(propertyName) — Indicates if the given property can be enumerated using the for-in statement (discussed later in this chapter). As with hasOwnProperty(), the property name must be a string.
- ? toLocaleString() — Returns a string representation of the object that is appropriate for the locale of execution environment.
- ? toString() — Returns a string representation of the object.
- ? valueOf() — Returns a string, number, or Boolean equivalent of the object. It often returns the same value as toString().
但是那些宿主对象host object并不一定含有,因为它们是由host implementation定义和提供,并不受ECMA-262管理,例如Dom,BOM 对象,它们可能不是继承于Object
在使用var object ={}来创建对象时,并没有调用Object()构造函数,同理用这种模式创建的数组也是没有调用构造函数
对象的属性分为数据属性和存取器属性,数据属性有四个内部属性,[[Configurable]], [[Enumerable]], [[Writable]] , [[Value]],value是该属性值的存储位置,想要修改这些内部属性需要使用 object.defineProperty()
var person = {};
Object.defineProperty(person, “name”, {
writable: false,
value: “Nicholas”
});
一旦configurable设为false,就无法再修改为true,调用这个函数时,参数默认为false,除非显式指定了true
-
? [[Configurable]] — Indicates if the property may be redefined by removing the property via delete, changing the property’s attributes, or changing the property into a data property. By default, this is true for all properties defined directly on an object.
-
? [[Enumerable]] — Indicates if the property will be returned in a for-in loop. By default, this is true for all properties defined directly on an object.
-
? [[Get]] — The function to call when the property is read from. The default value is undefined.
-
? [[Set]] — The function to call when the property is written to. The default value is undefined.
不可以直接定义一个存取器属性,也需要用object.defineProperty()
var book = {
_year: 2004,
edition: 1
};
Object.defineProperty(book, “year”, {
get: function(){
return this._year;
},
set: function(newValue){
if (newValue > 2004) {
this._year = newValue; this.edition += newValue - 2004;
}
}
});
book.year = 2005; alert(book.edition); //2
并不是一定要同时指定getter和setter,如果浏览器不支持object.defineProperty(),可以使用
__defineGetter__() and __defineSetter__()来指定getter和setter函数,但是configurable和enumerable就设定不了
一次性定义多个属性使用 Object.defineProperties()方法:
var book = {};
Object.defineProperties(book, {
_year: {
value: 2004
},
edition: {
value: 1
},
year: {
get: function(){
return this._year;
},
set: function(newValue){
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue - 2004;
}
}
}
});
对象 实例
原文:http://www.cnblogs.com/chuangweili/p/5164091.html