简体   繁体   English

如何定义不可扩展的javascript对象

[英]How to define a non-extensible javascript object

I'd like to, if possible, define a javascript object that has a few properties along with getters/setters for those properties, but I don't want others to be able to add new properties to objects without extending the object definition (similar to how one would define a class in Java/C#). 我想尽可能定义一个javascript对象,该对象具有一些属性以及这些属性的getter / setter,但是我不希望其他人能够在不扩展对象定义的情况下向对象添加新属性(类似如何在Java / C#中定义类)。 Is this possible to do with javascript? 这可能与javascript有关吗?

You can use the "preventExtensions" method. 您可以使用“ preventExtensions”方法。

var obj = { foo: 'a' };
Object.preventExtensions(obj);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions

In the following way, you can freeze the instances of the objects, but leave open to inheriting classes to add their own properties: 通过以下方式,您可以冻结对象的实例,但可以保留继承类以添加其自己的属性的权限:

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

See here: http://www.2ality.com/2013/06/freezing-instances.html 参见此处: http : //www.2ality.com/2013/06/freezing-instances.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM