Can somebody please explain to me why this simple piece of code is not working?
var user = {
    get name() {
        return this.name;
    },    
    set name(value) {
        this.name = value;
    }
};
user.name = 'David';
When I put this in the Firebug console in Firefox 21.0 it gives me this error:
InternalError: too much recursion
this.name = value;
Why? What is the proper way to define getters and setters in Javascript?
When you attempt to set name, the function will set this.name = value.
But the function is now attempting to set name. Therefore it will call the function again and set this.name to value.
But the function is now attempting to set name. Therefore it will call the function again and set this.name to value.
But the function is now attempting to set name. Therefore it will call the function again and set this.name to value.
....... SOME TIME LATER .......
But the function is now attempting to set name. Therefore it will call the function again and set this.name to value.
But the browser has determined that the call stack is too deep, the function has called itself too many times, and therefore to prevent a complete crash it causes the function to fail with the error you see.
Try using a different property name, such as this._name, to store and retrieve the value.
Your setter is calling itself.
Here's a solution :
var user = {
    get name() {
        return this._name;
    },    
    set name(value) {
        this._name = value;
    }
};
user.name = 'David';
Side note : Be careful that the get and set operators aren't supported in IE8.
Try,
var user = {
    get name() {
        return this._name;
    },    
    set name(value) {
        this._name = value;
    }
};
user.name = 'David';
Note the use of _name instead of name. Setting the value of name in the setter of name is a recursive call, hence the exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With