0

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
  }
});
einstein
  • 13,389
  • 27
  • 80
  • 110

1 Answers1

2

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 },
  • Sorry a typo. It should be this.name – einstein May 06 '13 at 14:47
  • I want `this.name` to be set when I use the `new Human({name: 'Einstein'})` – einstein May 06 '13 at 14:49
  • @Woho87: I know, but that's what causes the loop. If you want to use the `set` functionality, what you need is that when `.name` is set, your setter actually sets it to a different property. Then you set up a `get` for `.name` so that when you ask for the value of `.name` it'll get it from that other property. –  May 06 '13 at 14:51