如何在javascript中使对象的特定属性不可变?

时间:2017-03-17 09:24:12

标签: javascript

如果我有像

这样的对象
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不可变,以便其值不能被覆盖?

3 个答案:

答案 0 :(得分:9)

如果您已经拥有适当的资源,则可以将其描述符的writable属性修改为false,如下所示:

Object.defineProperty(person, 'firstName', {
      writable: false,
      configurable: false
});
应指定

configurable: false以防止将来修改firstName属性,例如将writable更改回true

阅读有关属性描述符的更多here

如果您之前定义了不存在的属性,那么所有描述符属性都默认为false,您需要指定的唯一内容是valueenumerable

Object.defineProperty(person, "firstName", {
    value: "Krishna",
    enumerable: true
});

答案 1 :(得分:2)

您有几个选项,但最简单的方法是制作只读,不可配置的属性:

let person = {
    lastName: 'Jai',
    age: 12
};
Object.defineProperty(person, "firstName", {
    value: "Krishna",
    enumerable: true
});

如上所述,当您定义新属性时,标记writableconfigurable都默认为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);