Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object literal notation getter and setter: too much recursion

I am new to scripting with js and following JavaScript guide of MDN. I am not able to understand some js concepts easily.

Tried the following code(from Java background) but it is giving too much recursion error by the browser.

//jshint esnext: true
console.clear();

var student = {
    get name() {
        return this.name;
    },

    set name(value) {//Should we not use same name as local variable?
        this.name = value;
    },

    get age() {
        return this.age;
    },

    set age(value) {
        this.age = value;
    }
};

var mike = Object.create(student);
console.log(mike.age);
console.log(mike.name);

mike.age = 29;
console.log(mike.age);

mike.name = "JS";
console.log(mike.name);

What is wrong with this?

like image 541
phoenix Avatar asked Sep 18 '25 19:09

phoenix


1 Answers

You should be referencing a private variable in the context of the getter and setter, instead of referencing the same name. A common pattern is to prefix each local variable with an underscore, compared to the public name.

var student = {
    get name() {
        return this._name;
    },

    set name(value) {//Should we not use same name as local variable?
        this._name = value;
    },

    get age() {
        return this._age;
    },

    set age(value) {
        this._age = value;
    }
};
like image 74
J3Y Avatar answered Sep 20 '25 10:09

J3Y