最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Object literal notation getter and setter: too much recursion - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Sep 22, 2015 at 8:50 phoenixphoenix 9953 gold badges19 silver badges39 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

You should be referencing a private variable in the context of the getter and setter, instead of referencing the same name. A mon pattern is to prefix each local variable with an underscore, pared 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;
    }
};
发布评论

评论列表(0)

  1. 暂无评论