javascript - getter setter Maximum call stack size exceeded Error -


i trying learn , set in javascript object tried

function ab(n){this.name=n;};  var c= new ab("abcde");   console.log(c); object.defineproperty(c, 'name', {     get: function() {         return name;     },     set: function(name) {        this.name = name;         } });  c.name="xyz";   console.log(c.name);  

here first making object using constructor , using , set. getting error "maximum call stack size exceeded". not getting reason of error .

i think has been explained, this.name = name in setter calls again setter, wich leads infinite recursion.

how 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 prototypal-approach
downside: private property _name 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 same thing prototypal aproach

class ab{     constructor(n){         this.name = n;     }      name(){ return this._name },     set name(value){ this._name = value } } 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -