Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use getters and setters in Javascript

Tags:

javascript

oop

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?

like image 829
David Barreto Avatar asked Jun 17 '13 15:06

David Barreto


3 Answers

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.

like image 100
Niet the Dark Absol Avatar answered Oct 26 '22 19:10

Niet the Dark Absol


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.

like image 31
Denys Séguret Avatar answered Oct 26 '22 21:10

Denys Séguret


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.

like image 39
chuckj Avatar answered Oct 26 '22 19:10

chuckj