> var a = {}
> Object.defineProperty(a, "b", {
... value: 110})
{}
> a
{}
> a.b
110
> a.b = 555
555
> a.b
110
> var aa = {b: 1}
undefined
> Object.defineProperty(aa, "b", {
... value: 119})
{ b: 119 }
> aa.b
119
> aa.b = 1
1
> aa.b
1
Why can aa.b be changed but a.b cannot?
The property descriptor has three properties:
configurable
enumerable
writable
. The default values are allfalse
, while the property descriptors defined using object literals are all
true
, which can be passedObject.getOwnPropertyDescriptor( a, 'b')
andObject.getOwnPropertyDescriptor(aa, 'b')
to get the descriptors of two properties.So
a.b
cannot be modified,aa.b
can be modified.Because by default, the property values of properties defined through
Object.defineProperty()
are allfalse
and are not writable.The properties defined through object literals are writable by default, call `
So the
b
property ofaa
is writable. SoObject.defineProperty()
does not change the attribute value of the property. So the value ofb
ofaa
will change.