數據屬性
- Configurable
表示能否通過delete刪除屬性,從而重新定義屬性,能否修改屬性的特性,或者能否把屬性修改為訪問器屬性。默認值為true
- Enumerable
表示能否通過for-in循環返回屬性。默認值為true
- Writable
表示能否修改屬性的值,默認值為true
- Value
包含這個屬性的數據值,默認值為undefined
定義屬性
var person = {}
Object.defineProperty{person, "name", {
writable: false,
value: "Nicholas"
}};
將configurable特性設置為false之后就不能再設置為true了
調用Object.defineProperty()方法創建一個新的屬性時,如果不指定,configurable,enumerable,writable特性的默認值都為false
訪問器屬性
- Configurable
- Enumerable
- Get
- Set
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
創建對象
工廠模式
function createPerson(name, age, job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function() {
alert(this.name);
}
return o;
}
var person1 = createPerson("Nicholas", 29, "Software Engineer");
var person2 = createPerson("Greg", 27, "Doctor");
構造函數模式
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function() {
alert(this.name);
}
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
// 實例對象的constructor(構造函數)屬性指向Person
alert(person1.consturctor == Person) // true
alert(person2.constructor == Person) // true
用new創建構造函數新實例,經歷4個步驟
- 創建一個新對象
- 將構造函數的作用域賦給新對象(this指向這個新對象)
- 執行構造函數中的代碼(為新對象添加屬性)
- 返回新對象
instanceof 操作符用于標識對象類型
alert(person1 instanceof Object); // true
alert(person1 instaceof Person); // true
原型模式
function Person () {}
Person.prototype.name = 'Nicholas';
Person.prototype.age = 29;
Person.prototype.job = 'Software Engineer';
Person.prototype.sayName = function() {
alert(this.name);
}
var person1 = new Person();
person1.sayName(); // 'Nicholas'
var person2 = new Person();
Person2.sayName(); // 'Nicholas'
可以通過isPrototypeOf()方法來確定對象之間的關系
alert(Person.prototype.isPrototypeOf(person1)) // true
alert(Person.prototype.isPrototypeOf(person2)) // true
可以通過Object.getPrototypeOf()方法返回[[prototype]]的值
alert(Object.getPrototypeOf(person1) == Person.prototype) // true
alert(Object.getPrototypeOf(person1).name) // true
通過hasOwnProperty()方法檢測屬性是否存在實例中
person1.name = 'Greg';
alert(person1.hasOwnProperty("name")) // true
delete(person1.name)
alert(person1.hasOwnProperty("name")) // false
in操作符,通過對象能夠訪問到給定屬性時返回true
alert(person1.hasOwnProperty("name")) // false
alert("name" in person1) // true