Doubt POO Javascript

Asked

Viewed 74 times

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)

1 answer

1


You need to keep in mind that in Javascript some things are different from most languages that work with OO. Properties are defined members directly on the objects and not in the classes as it would be in other languages.

Therefore, the first parameter of Object.defineProperty is the object where the property will be defined, not a class definition. In your attempt, instead of passing the object you pass the function that defines the class.

In the example below, the object a contains the property discount, already the object b nay.

function Product(name) {
    this.name = name
}

var a = new Product('Teste 1')
var b = new Product('Teste 1')

Object.defineProperty(a, 'discount', {
    get: function () {
        return 'TESTE' 
    }
})

console.log(a.discount)
console.log(b.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'?

  • @Lucasstellet You do as in your first example. There the defineProperty will run for all objects that are created...

  • Thanks for the help! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.