Avoid Adding Methods And Properties To Custom Object
I'm using a base custom object extended with prototype function Person() {} Person.prototype.Name = ''; Person.prototype.Lastname = ''; var NewPerson= new Person(); NewPer
Solution 1:
I found freeze and seal but those prevent me from changing the values.
Values can be changed with Object.seal
The Object.seal() method seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable. Values of present properties can still be changed as long as they are writable.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal
http://plnkr.co/edit/Wut7lsOxdFuz2VzsFzCM?p=preview
functionPerson(){
this.name = "";
this.id = "";
Object.seal(this);
}
var p1 = newPerson();
p1.name = "Mike";
p1.id = "A1";
p1.age = 32;
console.log(p1); //Person {name: "Mike", id: "A1"}
If you desire to actually freeze the prototype of the object while leaving other parts writable then you can try this approach
functionPerson(){
this.name = "";
this.id = "";
Object.seal(this);
}
//this will add to PersonPerson.prototype.test = function(){
alert("hi");
}
Object.freeze(Person.prototype);
//this won'tPerson.prototype.test2 = function(){
alert("hi");
}
var p1 = newPerson();
p1.name = "Mike";
p1.id = "A1";
p1.age = 32;
console.log(p1); //Person {name: "Mike", id: "A1"} test will be on the proto
Post a Comment for "Avoid Adding Methods And Properties To Custom Object"