ECMAScript 5新增了很多物件方法(Object Methods)
var user = {
name: 'Shawn',
age: 18,
language: 'zh-tw'
};
語法: Object.defineProperty(object, property, {value : value});
Object.defineProperty(user, 'language', { value: 'en' });
- writable: 屬性 value 是否可寫入
- enumerable: 屬性可否可被列舉
- configurable: value以外的屬性可否重新配置
- get: Getter
- set: Setter
Object.defineProperty(user, 'language', { writable: false });
user.language = '123'; // 無作用
Object.defineProperty(user, 'language', { enumerable: false });
Object.keys(user); // 不可列舉 language, 所以沒有 language
Object.defineProperty(user, 'language', { configurable: false });
Object.defineProperty(user, 'language', { get: function () { return language } }); // 無作用
語法: Object.getOwnPropertyNames(object);
Object.getOwnPropertyNames(user); // 可取得所有屬性,包括 enumerable = false 的屬性
語法: Object.keys(object);
Object.keys(user);
語法: Object.getOwnPropertyNames(object);
JSON.stringify(Object.getOwnPropertyDescriptor(user, 'name')); // 取得 name 的中繼資料
語法: Object.getPrototypeOf(object);
function Person(name, age, language) {
this.name = name;
this.age = age;
this.language = language;
};
var user2 = new Person('Koji', 20, 'jp');
console.log(Object.getPrototypeOf(user2)); // 用 log 才看的到
語法: Object.preventExtensions(object);
Object.preventExtensions(user2);
Object.defineProperty(user2, 'nationality', { value: 'tw' }); // 無作用
語法: Object.isExtensible(object);
Object.isExtensible(user2); // false
Object.seal(user2);
user2.phone = '0900123456';
document.getElementById('demo8').textContent = JSON.stringify(user2); // phone 未加入
語法: Object.isSealed(object);
Object.isSealed(user2);
語法: Object.freeze(object);
user2.name = 'test';
user2.name; // 不會被改成test
語法: Object.isFrozen(object);