1、“點(diǎn)”語(yǔ)法
// ECMAScript 3
// 設(shè)置屬性
obj.someKey = 'Hello World!';
// 獲取屬性
var val = obj.someKey;
2、中括號(hào)語(yǔ)法
// ECMAScript 3
// 設(shè)置屬性
obj['someKey'] = 'Hello World';
// 獲取屬性
var val = obj['someKey'];
3、Object.defineProperty
// ECMAScript 5
// 設(shè)置屬性
Object.defineProperty(obj, 'someKey', {
value: 'Hello World!',
writable: true,
enumerable: true,
configurable: true
})
// 當(dāng)然,我們可以重新封裝一個(gè)簡(jiǎn)單的方法來(lái)實(shí)現(xiàn)
const defineProp = function(obj, key, value) {
const config = { value }
Object.defineProperty(obj, key, config)
}
// 使用上述的方法,我們需要先創(chuàng)建一個(gè)空的對(duì)象
const person = Object.create(null);
// 然后設(shè)置對(duì)象的各個(gè)屬性
defineProp(person, 'name', 'Johnny');
defineProp(person, 'age', 18);
defineProp(person, 'rich', true);
// 獲取屬性:可以用1和2中獲取屬性的方式來(lái)獲取屬性
這個(gè)方法可以用于實(shí)現(xiàn)繼承
// 1、創(chuàng)建程序員對(duì)象programer,同時(shí)繼承person對(duì)象
const programer = Object.create(person);
// 2、為programer對(duì)象設(shè)置一個(gè)屬性
defineProp(programer, 'skill', 'javascript')
// 3、獲取繼承自person的name屬性
console.log(programer.name);
// 4、獲取programer自身的skill屬性
console.log(programer.skill);
4、Object.defineProperties
// ECMAScript 5
// 設(shè)置屬性
Object.defineProperties(obj, {
'key1': {
value: 'Hello World',
writable: true
},
'key2': {
value: 'Hi, Johnny',
writable: false
}
});
// 獲取屬性:可以用1和2中獲取屬性的方式來(lái)獲取屬性