我正在使用使用原型(prototype)扩展的基本自定义对象
function Person() {}
Person.prototype.Name = "";
Person.prototype.Lastname = "";
var NewPerson= new Person();
NewPerson.Name = "Nancy";
NewPerson.Lastname = "Drew"; //<--- right way
NewPerson.lastname = "Drew"; //<--- wrong property
我需要避免在定义的对象中添加新属性和方法,因为它会产生静默错误和错误。
我知道 javascript 有一种糟糕的方式来管理类/对象,但有一种方法可以保护它吗?
我找到了freeze 和seal 但它们阻止我更改值。
最佳答案
I found freeze and seal but those prevent me from changing the values.
可以使用 Object.seal 更改值
Object.seal() 方法密封对象,防止向其添加新属性并将所有现有属性标记为不可配置。 当前属性的值仍然可以更改,只要它们是可写的。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal
http://plnkr.co/edit/Wut7lsOxdFuz2VzsFzCM?p=preview
function Person(){
this.name = "";
this.id = "";
Object.seal(this);
}
var p1 = new Person();
p1.name = "Mike";
p1.id = "A1";
p1.age = 32;
console.log(p1); //Person {name: "Mike", id: "A1"}
如果你想真正卡住对象的原型(prototype),同时让其他部分可写,那么你可以尝试这种方法
function Person(){
this.name = "";
this.id = "";
Object.seal(this);
}
//this will add to Person
Person.prototype.test = function(){
alert("hi");
}
Object.freeze(Person.prototype);
//this won't
Person.prototype.test2 = function(){
alert("hi");
}
var p1 = new Person();
p1.name = "Mike";
p1.id = "A1";
p1.age = 32;
console.log(p1); //Person {name: "Mike", id: "A1"} test will be on the proto
关于javascript - 避免向自定义对象添加方法和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30709191/