You have a couple of options, but probably the simplest is to make a read-only, non-configurable property:
let person = {
lastName: 'Jai',
age: 12
};
Object.defineProperty(person, "firstName", {
value: "Krishna",
enumerable: true
});
The flags writable and configurable both default to false when, as above, you're defining a new property. (You don't have to make it enumerable, as far as that goes, but...)
Example:
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();
Or if you want to apply the change after the fact, you need to specify the flags:
let person = {
firstName: "Krishna",
lastName: 'Jai',
age: 12
};
Object.defineProperty(person, "firstName", {
writable: false,
configurable: false
});
Example:
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();
Stringtype. The right phrase should be read only and non-configurable property.