一個可能的方法與Object.defineProperty()定義在init()
這個屬性爲不可寫:
Car.prototype = {
init: function() {
Object.defineProperty(this, 'country', {
value: this.country,
enumerable: true, // false if you don't want seeing `country` in `for..of` and other iterations
/* set by default, might want to specify this explicitly
configurable: false,
writable: false
*/
});
},
country: 'Ireland',
};
這種方法有一個非常有趣的功能:您可以通過調整原型財產,而且會影響到所有的對象從那時起創建:
var c1 = new Car();
c1.country = 'England';
console.log(c1.country); // Ireland
c1.__proto__.country = 'England';
console.log(c1.country); // Ireland
var c2 = new Car();
console.log(c2.country); // England
如果你不希望這樣的事情發生,無論是防止Car.prototype
修改,或將country
成私有變量功能,像這樣:
Car.prototype = {
init: function() {
var country = 'Ireland';
Object.defineProperty(this, 'country', {
value: country,
});
}
};
的可能的複製[?如何創建JavaScript常量使用const關鍵字對象的屬性(https://stackoverflow.com/questions/10843572/how-to-create-javascript -constants-as-properties-of-objects-using-const-keyword) –