1

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?

4
  • remove this from b. set it as b=value in set method, let me know if works. Commented Sep 6, 2016 at 11:54
  • which is your browser? is it compatible with defineProperty? Commented Sep 6, 2016 at 11:54
  • i am not doing this on browser. i am using node's repl. @RicardoPontual Commented Sep 6, 2016 at 11:55
  • @DeendayalGarg by using this i am unable to change the value as my get function always return me 5 Commented Sep 6, 2016 at 11:57

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

i just not get it . how setter is in infinite loop??
@AtulAgrawal I add some more information, check if it is clear now.
@AtulAgrawal great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.