The question is published on by Tutorial Guruji team.
What is the Difference between Object.defineProperty(obj, 'x', ...)
and obj.x
?
From MDN, in non-strict mode:
var obj = { }; Object.preventExtensions(obj); Object.defineProperty(obj, 'x', { value: "foo" } );
throws an error Cannot add property x, object is not extensible. But obj.x = 'foo'
does not throw any error. I don’t understand the difference in behavior.
Answer
Neither technique will work.
What you are seeing is simply that trying to call .defineProperty
on an object that has had .preventExtensions
called on it, throws an error and when you use the implicit syntax of obj.x = foo
, it silently fails. Silent failures happen quite frequently when you are not in strict mode, which is one of the main benefits of "use strict"
.
Many of the static Object
methods (.preventExtensions
, .freeze
, .seal
, etc.) were added with ES 2015 along with "use strict"
to help bring JavaScript into the modern era. With these new capabilities, we move farther and farther away from some of the native behaviors that have been with JavaScript since the beginning.
"use strict" var obj = { }; Object.preventExtensions(obj); // This won't work no matter what mode your in. "use strict" will // at least make it throw an error rather than silently fail. obj.x = "foo";
Additionally, with .defineProperty
, there are 3 other things that you can configure about the property besides its value:
- configurable
- enumerable
- writable
When you just create a new property, with object.property = foo
, you are only setting the value and getting the default values for the other 3 configurations.