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 badges1 Answer
Reset to default 12You 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;
}
};