3

I'm using a base custom object extended with 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

I need to avoid to add new properties and methods in a defined object because it would generate silent errors and bugs.

I know that javascript has a terrible way to manage classes/objects, but there's a way to protect it?

I found freeze and seal but those prevent me from changing the values.

1
  • 2
    The recommended way is to pass initial values as arguments to the constructor and create the properties there. Commented Jun 8, 2015 at 13:55

1 Answer 1

6

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

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"}

If you desire to actually freeze the prototype of the object while leaving other parts writable then you can try this approach

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
Sign up to request clarification or add additional context in comments.

2 Comments

It works this way, but not if I extend it with Person.prototype. I tried Object.seal(Person);
I've updated the answer to demonstrate freezing the prototype and sealing in the constructor. The combination of these two approaches gets you very close to what you need (I think).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.