[英]How to define a non-extensible javascript object
我想盡可能定義一個javascript對象,該對象具有一些屬性以及這些屬性的getter / setter,但是我不希望其他人能夠在不擴展對象定義的情況下向對象添加新屬性(類似如何在Java / C#中定義類)。 這可能與javascript有關嗎?
您可以使用“ preventExtensions”方法。
var obj = { foo: 'a' };
Object.preventExtensions(obj);
通過以下方式,您可以凍結對象的實例,但可以保留繼承類以添加其自己的屬性的權限:
function Animal(name, action) {
this.name = name;
this.action = action;
if (this.constructor === Animal) {
Object.freeze(this);
}
}
var dog = new Animal('rover', 'bark')
dog.run = function(){console.log('I\'m running!')} // throws type error
function Dog(name, action, bark) {
Animal.call(this, name, action)
this.bark = bark // Animal not frozen since constructor is different
Object.freeze(this)
}
var puppy = new Dog('sparky', 'run', 'woof')
puppy.isTrained = false; // throws type error
參見此處: http : //www.2ality.com/2013/06/freezing-instances.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.