如果我有像
这样的对象let person = {
firstName: 'Krishna',
lastName: 'Jai',
age: 12
}
person.firstName = 'Kumar';
console.log(person);
//output
Object { firstname: 'Kumar', lastName: 'Jai', age: 12 }
但我不应该让任何用户更改person的firstName。如何使firstName不可变,以便其值不能被覆盖?
答案 0 :(得分:9)
如果您已经拥有适当的资源,则可以将其描述符的writable
属性修改为false
,如下所示:
Object.defineProperty(person, 'firstName', {
writable: false,
configurable: false
});
应指定 configurable: false
以防止将来修改firstName
属性,例如将writable
更改回true
。
阅读有关属性描述符的更多here。
如果您之前定义了不存在的属性,那么所有描述符属性都默认为false
,您需要指定的唯一内容是value
和enumerable
:
Object.defineProperty(person, "firstName", {
value: "Krishna",
enumerable: true
});
答案 1 :(得分:2)
您有几个选项,但最简单的方法是制作只读,不可配置的属性:
let person = {
lastName: 'Jai',
age: 12
};
Object.defineProperty(person, "firstName", {
value: "Krishna",
enumerable: true
});
如上所述,当您定义新属性时,标记writable
和configurable
都默认为false
。 (你不 使其可枚举,就此而言......但是......)
示例:
let person = {
lastName: 'Jai',
age: 12
};
Object.defineProperty(person, "firstName", {
value: "Krishna",
enumerable: true
});
console.log("before: ", person.firstName);
person.firstName = "Mohinder";
console.log("after setting in loose mode:", person.firstName);
function foo() {
"use strict";
console.log("trying to set in strict mode:");
person.firstName = "Mohinder"; // Error
}
foo();
或者如果您想在事后应用更改,则需要指定标志:
let person = {
firstName: "Krishna",
lastName: 'Jai',
age: 12
};
Object.defineProperty(person, "firstName", {
writable: false,
configurable: false
});
示例:
let person = {
firstName: "Krishna",
lastName: 'Jai',
age: 12
};
Object.defineProperty(person, "firstName", {
writable: false,
configurable: false
});
console.log("before: ", person.firstName);
person.firstName = "Mohinder";
console.log("after setting in loose mode:", person.firstName);
function foo() {
"use strict";
console.log("trying to set in strict mode:");
person.firstName = "Mohinder"; // Error
}
foo();
答案 2 :(得分:0)
您可以使用getter method并省略设置器。
let person = {
get firstName() { return 'Krishna'; },
lastName: 'Jai',
age: 12
};
person.firstName = 'Kumar';
console.log(person);