E
E
Eugene-1232019-07-14 15:05:15
JavaScript
Eugene-123, 2019-07-14 15:05:15

Why should I use this if there are closures?

Let's say I have two functions that create an object:

// Функция №1
function square(_a, _b) {
    let a    = _a; 
    let b    = _b;
    let area = 0;
    let obj = {
        computeArea: function() {
            area = a * b;
        },
        getArea: function() { return area; },
        get a()       { return a;  },
        set a(value)  { a = value; },
        get b()       { return b;  },
        set b(value ) { b = value; }
    };
    return obj;
}

// Функция №2
function Square(a, b) {
    this.a = a;
    this.b = b;
    this.area = 0;
    this.computeArea = function() {
        this.area = this.a * this.b;
    };
}


I understand that the second option is written shorter. However, why should I use this? What are the disadvantages of the first option?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Victor Bomberow, 2019-07-14
@majstar_Zubr

Less code means fewer bugs;
Less code is faster to write;
Less code is easier to understand;
Using language constructs for their intended purpose better expresses intent;

A
Anton Shvets, 2019-07-14
@Xuxicheta

In the first case, you have created "private fields". You can do whatever you like, but storing data in the properties of an object is simply more convenient and clearer. And there is no way to accidentally hook an external variable into a closure, then try to find one.

M
Max, 2019-07-14
@mbelskiy

The first thing that comes to mind is:
- when creating instances of an object through closures, the advantages of prototype inheritance are lost (methods are declared on an instance)
- the ability to identify an instance by the `typeof` operation is lost

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question