我有一个具有某些属性的类,并基于它们创建了新对象。在创建对象后,我不希望一个对象将某些属性添加到类中。我试过对象冻结对象。但它不起作用。想知道是否有办法这样做?
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
答案 0 :(得分:1)
您正在尝试(不)更改原型对象,因此您必须改为冻结原型对象:
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);