Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeze JavaScript Object

Tags:

javascript

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
like image 903
Shrujan Shetty Avatar asked Feb 23 '26 14:02

Shrujan Shetty


1 Answers

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);
like image 159
CertainPerformance Avatar answered Feb 25 '26 03:02

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!