gpt4 book ai didi

javascript - 卡住 JavaScript 对象

转载 作者:行者123 更新时间:2023-11-29 15:15:18 25 4
gpt4 key购买 nike

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

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)对象:

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);

关于javascript - 卡住 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49935639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com