Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/440.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
冻结JavaScript对象_Javascript - Fatal编程技术网

冻结JavaScript对象

冻结JavaScript对象,javascript,Javascript,我有一个具有某些属性的类,并基于它们创建了新对象。我不希望一个对象在创建对象后将某些属性添加到类中。我试过冻结这个物体。但它不起作用。我想知道是否有办法做到这一点 function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } var myFather = new Person

我有一个具有某些属性的类,并基于它们创建了新对象。我不希望一个对象在创建对象后将某些属性添加到类中。我试过冻结这个物体。但它不起作用。我想知道是否有办法做到这一点

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
您正在尝试(不)更改prototype对象,因此必须冻结prototype对象:

职能人员(第一、最后、年龄、眼睛){
this.firstName=first;
this.lastName=last;
这个。年龄=年龄;
this.eyeColor=眼睛;
}
var myFather=新人(“约翰”、“多伊”、50、“蓝色”);
var myMother=新人(“萨利”,“拉力赛”,48,“绿色”);
Object.freeze(Person.prototype);//现在它确实起作用了
Person.prototype.favColor='绿色';

console.log(我的母亲)不要使用类,使用对象。为这样的数据结构使用类不会带来任何好处,也会使代码变得不必要的复杂。编写
函数人(first,last,age,eye){return{first,last,age,eye};}
非常简单。感谢您的回复。。。出于好奇,是否只有myFather对象可以继承新属性而不是myMother对象?您可以创建扩展Person的新类,并冻结一个子类的原型,而不冻结另一个子类的原型,但是
object.freeze(MotherClass.prototype)
显然只适用于MotherClass,而不适用于Person。不过最好避免继承链。@ShrujanShetty这似乎是一个XY问题。你为什么要那样做?如果有许多父对象具有除person或mother之外的其他属性,则创建person的子类。这就是OO的全部要点。我也强烈反对你应该避免继承链。