1
I am practicing POO in Javascript and, looking for some examples on the internet, I came across the practice below:
function Product(name, price) {
this.name = name;
this.price = price;
//this.discount = 0; // <- remove this line and refactor with the code below
var _discount; // private member
Object.defineProperty(this, "discount", {
get: function () { return _discount; },
set: function (value) { _discount = value; if (_discount > 80) _discount = 80; }
});
}
// the client code
var sneakers = new Product("Sneakers", 20);
sneakers.discount = 50; // 50, setter is called
sneakers.discount += 20; // 70, setter is called
sneakers.discount += 20; // 80, not 90!
console.log(sneakers.discount); // getter is called
I repeated the example without looking at it and worked in a good.
However, when I tried a different approach to the same example, I already got lost a little.
What I tried to do was instead of defining a new property using the 'defineProperty' method within the constructor function, define externally, as if I were to implement this property a while later.
Only the log is giving 'Undefined'.
Could someone help me? I’ve just been practicing POO.
Follow the different approach I tried:
function Product(name, price) {
this.name = name;
this.price = price;
var _discount;
}
Object.defineProperty(Product, 'discount', {
get: function () {
return this._discount;
},
set: function (value) {
_discount = value;
if (_discount > 80) {
_discount = 80;
}
}
})
var television = new Product('samsung_a3045', 1000);
television.discount += 50;
console.log(television.discount)
What if I want to 'export' this new property to another object that has the same constructor base? That is, another object created with the function 'Product'?
– Lucas Stellet
@Lucasstellet You do as in your first example. There the defineProperty will run for all objects that are created...
– Jéf Bueno
Thanks for the help! :)
– Lucas Stellet