How to set default value with an accessor value in Object.defineProperties?

StackOverflow https://stackoverflow.com/questions/16401165

  •  14-04-2022
  •  | 
  •  

سؤال

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
  }
});
هل كانت مفيدة؟

المحلول

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 },
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top