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?
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;
}
};
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