Question

I want to be able to set new name upon instanciation of a new object. But somehow I got an infinite loop to be happening. I dont know how to fix it.

function Human(opt) {
  this.name = opt.name; //this causes ranger error or infinite loop
}

Object.defineProperties(Human.prototype, {
  name : {
    set : function(val) {
      if(name === 'Einstein') {
        console.log('Hello Einstein');
      }
      this.name = val;
    },
    configurable : false
  }
});
Was it helpful?

Solution

There's no infinite loop in your code, but there would be if you changed this:

this.end = val;

to this:

this.name = val;

(Question now updated to use this.name = val;)

Because it would of course call the set again, and again...

What you need is something like your .end property to store the actual value, and then use a get accessor to retrieve the value from .end.

  get: function() { return this.end },
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top