I think it has already been explained, that this.name = Name
in the setter calls again the setter, wich leads to an infinite recursion.
How about this aproach:
function Ab(_name){
Object.defineProperty(this, "name", {
//enumerable: true, //maybe?
get: function(){ return _name },
set: function(value){ _name = value }
});
}
var c = new Ab("abcde");
console.log(c, c.name);
Or the prototypal-approach
downside: the private property _name
is a public
function Ab(n){
this.name = n;
}
Object.defineProperty(Ab.prototype, "name", {
get: function(){ return this._name },
set: function(value){ this._name = value }
});
Or ES6
pretty much the same thing as the prototypal aproach
class Ab{
constructor(n){
this.name = n;
}
get name(){ return this._name },
set name(value){ this._name = value }
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…