Atul Agrawal Atul Agrawal - 2 months ago 12
Javascript Question

unable to set property in an object using defineProperty method

I have defined an object and defining a property using javascript's defineProperty method.

var obj ={};
Object.defineProperty(obj,'b',{get:function(){
return 5},
set:function(value){
this.b = value}
});


but when i am setting the value of b using below statement

obj.b = 25


it giving me

RangeError: Maximum call stack size exceeded

How can i set the value of b?

Answer

You are using setter in infinite recursive loop, code inside setter is using it again:

this.b = value; //this use setter of b again

change it to any different variable name like:

this.bVal=value;

All code:

//example object
obj={};

Object.defineProperty(obj,'b',{
get:function(){
  return this.bVal;
},
set:function(value){
  this.bVal=value;
}
});

obj.b="Test text value of property b";
console.log(obj.b);

Why previous code was infinite loop? Take a look:

obj.b=12; //this code run set function

Inside set function was:

this.b=value; //this code also runs set function because this===obj

So set function is called again and again and never stops.

Comments