Roli Agrawal Roli Agrawal - 1 year ago 227
Javascript Question

getter setter Maximum call stack size exceeded Error

I am trying to learn get and set in JavaScript object for that I tried

function ab(n){;};
var c= new ab("abcde");
Object.defineProperty(c, 'name', {
get: function() {
return name;
set: function(Name) { = Name;

Here I am first making object using constructor and then using get and set. But i am getting error "Maximum call stack size exceeded". I am not getting the reason of This Error . Thanks for help

Answer Source

I think it has already been explained, that = Name in the setter calls again the setter, wich leads to an infinite recursion.

How about this aproach:

function Ab(_name){
    Object.defineProperty(this, "name", {
        //enumerable: true, //maybe?
        get: function(){ return _name },
        set: function(value){ _name = value }

var c = new Ab("abcde");

Or the prototypal-approach
downside: the private property _name is a public

function Ab(n){ = n;
Object.defineProperty(Ab.prototype, "name", {
    get: function(){ return this._name },
    set: function(value){ this._name = value }

Or ES6
pretty much the same thing as the prototypal aproach

class Ab{
    constructor(n){ = n;

    get name(){ return this._name },
    set name(value){ this._name = value }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download