Answer the question
In order to leave comments, you need to log in
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;
};
}
Answer the question
In order to leave comments, you need to log in
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;
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question