Reputation: 1888
In js I have created an object. I want to add a new property to the object's prototype and the property will be different from instance to instance. Now to add value I used get. But it gives me error. I have added the code below.
How can I accomplish this thing?
I have googled this. And all I have learned is by get they add value to an existing property. But I want to add value to the new property and that will vary instance to instance.
var computer = function (name, ram) {
this.name = name;
this.ram = ram;
};
Object.defineProperty(computer.prototype, "graphic", {
set: function graphic(value) {
this.graphic = value;
},
get: function graphic() {
return this.graphic;
},
});
var vio = new computer("sony", "8gb");
vio.graphic = "gtx980";
console.log(vio.graphic);
The error massage:
Upvotes: 0
Views: 66
Reputation: 174967
Rereading your question, I'll answer the actual concern:
When you put things on the prototype, they are shared between all instances (as though you add them to the class in a classical language like Java).
When you put things on this
, they are only accessible for the specific instance.
The following works, without setters or getters:
function Computer(name, ram) { // Please use Capital names for constructors
this.name = name;
this.ram = ram;
};
let vio = new Computer('sony', '8gb');
vio.graphic = 'gtx980';
The graphic
property will only exist for the instance held in vio
, not every computer instance out there.
If, on the other hand you were to do this:
function Computer(name, ram) {
this.name = name;
this.ram = ram;
}
Computer.prototype.graphic = 'gtx980';
// All instances of Computer will now have a .graphic with the value of 'gtx980'.
The reason you're getting the error is that you define a setter for graphic
, in it, you're trying to assign to graphic
which invokes the setter for graphic
which tries to assign to graphic
which invokes.... you get the point.
The solution is to change the name of the actual variable (to, say _graphic
).
var computer = function (name, ram) {
this.name = name;
this.ram = ram;
};
Object.defineProperty(computer.prototype, "graphic", {
set: function graphic(value) {
this._graphic = value;
},
get: function graphic() {
return this._graphic;
},
});
var vio = new computer("sony", "8gb");
vio.graphic = "gtx980";
console.log(vio.graphic);
Note that JS doesn't really have private variables. You won't be able to prevent someone from changing _graphic
.
Upvotes: 1