Shrujan Shetty
Shrujan Shetty

Reputation: 2392

Freeze JavaScript Object

I have a class with certain properties and have created new objects based on them. I don't want one object to have certain property added to the class after I have created the object. I have tried object freezing the object. But it does not work. Was wondering if there was a way to do so?

function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
Object.freeze(myMother); // does not work

Person.prototype.favColor = 'green'; // this is reflected in myMother object as well which i don't want

Upvotes: 3

Views: 160

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370789

You're trying to (not) change the prototype object, so you have to Freeze the prototype object instead:

function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
Object.freeze(Person.prototype); // now it does work

Person.prototype.favColor = 'green';
console.log(myMother);

Upvotes: 1

Related Questions