The static method Object.defineProperty() defines a new property directly on an object, or modifies an existing property on an object, and returns the object.
Example 1 - Creating a property
var user = {
firstName : 'Ramesh',
lastName : 'Fadatare',
emailId : 'ramesh@gmail.com',
age : 29
};
function test(){
Object.defineProperty(user, 'fullName', {
value: user.firstName + " " + user.lastName
});
console.log(user.fullName);
}
test();
Output:
Ramesh Fadatare
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.
Example 2 - Modifying a property
var o = {}; // Creates a new object
Object.defineProperty(o, 'a', {
value: 37,
writable: false
});
console.log(o.a); // logs 37
o.a = 25; // No error thrown
// (it would throw in strict mode,
// even if the value had been the same)
console.log(o.a); // logs 37. The assignment didn't work.
// strict mode
(function() {
'use strict';
var o = {};
Object.defineProperty(o, 'b', {
value: 2,
writable: false
});
o.b = 3; // throws TypeError: "b" is read-only
return o.b; // returns 2 without the line above
}());
Comments
Post a Comment
Leave Comment