0

I am a newbie to JavaScript. I created a constructor function and an object using the constructor. The code is as below

var Cell = function Cell(make, model, price){
  this.make = make;
  this.model = model;
  this.price = price;
}

var motog = new Cell('Motorola', 'moto g', 14000);

Object.defineProperties(motog, {
  "make": { 
    get: function() { 
      console.log('make getter called'); 
      return this.make; 
    },
    set: function(make) { 
      console.log('make setter called'); 
      this.make = make; 
    }
  },
  "model": { 
    get: function() { 
      console.log('model getter called'); 
      return this.model; 
    },
    set: function(model) { 
      console.log('model setter called'); 
      this.model = model; 
    }
  }
});

console.log('------------------1');
console.log(motog.make);
console.log('------------------2');
motog.make = 'Google';

I have added the log statements in getters and setters to see the trace of execution. My questions are:

1) Objects can be created either by using constructors or by object initializers(declaring property and its value). Is the above way of adding getters and setters right for objects created using constructor function?

2) When I run the above code, it goes into infinite loop printing the log statement from the getter of 'make'. The loop terminates as below. Whats wrong with the code?

make getter called
make getter called
make getter called

RangeError: Maximum call stack size exceeded
    at String.replace (native)
    at Console.exports.format (util.js:35:23)
    at Console.log (console.js:53:34)
    at Cell.Object.defineProperties.make.get [as make

Thanks.

1 Answer 1

1

Define the properties on the prototype, not the instance:

Object.defineProperties(Cell.prototype, {
  ...

You get an infinite loop because this.make is the same make property you're defining.

Sign up to request clarification or add additional context in comments.

1 Comment

Because of how the prototype chain works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.