📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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