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.