Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

JavaScript | Object.defineProperty() Method

  • Last Updated : 16 Apr, 2020

The Object.defineProperty() method in JavaScript is a Standard built-in objects which defines a new property directly on an object and returns the object.

Syntax:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Object.defineProperty(obj, prop, descriptor)

Parameter: This method accept three parameters as mentioned above and described below:

  • Obj: This parameter holds the Object on which user is going to be define the property.
  • Prop: This parameter holds the name of a property which is going to be defined or modified.
  • Descriptor: This parameter holds the descriptor for the property being defined or modified.

Return Value: This method returns the object which is passed as the argument to the function.



Below examples illustrate the Object.defineProperty() method in JavaScript:

Example 1:




<script>
const geek1 = {};
Object.defineProperty(geek1, 'prop1', {
  value: 65,
  writable: false
});
geek1.prop1 = 7;
console.log(geek1.prop1);
  
const geek2 = {};  
Object.defineProperty(geek2, 'prop2', {  
      
  value: 54,  
  value: 23,  
  value: 12*9,  
  });  
geek2.prop2 ;  
console.log(geek2.prop2); 
</script> 

Output:

65
108

Example 2:




<script>
function gfg() {
}
  
var result;
Object.defineProperty(gfg.prototype, "valx", {
  get() {
    return result;
  },
  set(valx) {
    result = valx;
  }
});
  
var vala = new gfg();
var valb = new gfg();
vala.valx = 6;
console.log(valb.valx);
  
function gfg1() {
}
  
gfg1.prototype.valx = 4;
Object.defineProperty(gfg1.prototype, "valy", {
  writable: false,
  value: 8
});
  
var vala = new gfg1();
vala.valx = 4;
console.log(vala.valx); 
console.log(gfg1.prototype.valx); 
vala.valy = 2;
console.log(vala.valy);
console.log(gfg1.prototype.valy);
</script> 

Output:

6
4
4
8
8

Supported Browsers: The browsers supported by Object.defineProperty() method are listed below:

  • Google Chrome
  • Firefox
  • Opera
  • Safari
  • Edge



My Personal Notes arrow_drop_up
Recommended Articles
Page :