JavsScript中的数据属性和构造器属性

'use strict';

var person = new Object();
Object.defineProperties(person, {
    username: {
        configurable: true,
        enumerable: true,
        writable: false,
        value: '洛神赋'
    },
    password: {
        configurable: true,
        enumerable: true,
        writable: true,
        value: '123456'
    },
    _hometown: {
        configurable: true,
        enumerable: true,
        value: '武汉'
    },
    hometown: {
        get: function() {
            return this._hometown;
        }
    }
});

console.log(person);
try {
    person.username = '骆浩';
} catch(ex) {
    console.log('username的writable特性是false,因此不可以修改。');
}

console.log(person.hometown)
try {
    person.hometown = '北京';
} catch(err) {
    console.log('cannot set property hometown which has only a getter');
}

console.log(person.hometown);

 

你可能感兴趣的:(JavaScript)