简体   繁体   中英

defining a property in an object before using object.defineProperty method

I've read the documentation of MDN about the Object.defineProperty , but I have two questions:

let person = {name: 'Prabu', age:30};
Object.defineProperty(person, 'name', {
    writable:false, 
    enumerable: false,
    configurable: false
});

The first question:

is the above code acceptable? in other words, do I have to define the "value" attribute of the 'name' property inside the Object.defineProperty method? or I can define the "value" of the 'name' property inside the object literal directly just like the thing I am doing in my code?

The second question:

Doing it this way (my code), will any browser set (overwrite) the "value" of the property 'name' to undefined because I'm not assigning the value of it inside the Object.defineProperty method?

Your code does what you're expecting it to. The property starts out as a writable, enumerable, configurable property, and then you change the property descriptor while keeping its value as Prabu .

 'use strict'; let person = {name: 'Prabu', age:30}; Object.defineProperty(person, 'name', { writable:false, enumerable: false, configurab: false }); console.log(person.name);

But it would probably be more appropriate to assign the value and desired descriptor at once, by putting a value property in the descriptor:

 'use strict'; let person = {age:30}; Object.defineProperty(person, 'name', { writable:false, enumerable: false, configurable: false, value: 'Prabu', }); console.log(person.name);

will any browser set (overwrite) the "value" of the property 'name' to undefined because I'm not assigning the value of it inside the Object.defineProperty method?

No, any remotely standards-compliant browser will preserve the value that was previously assigned. This process is described by the specificationin ValidateAndApplyPropertyDescriptor .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM