Recently, in many articles (on Habré and not only) I often see examples of the emulation of private properties of objects in JS through closures. The authors usually explain this by their desire to use such an OOP mechanism as
encapsulation , and thereby guarantee the work with the object solely through its methods, without directly affecting the properties.
In this article, I propose to objectively consider the advantages and disadvantages of such an approach, so that everyone can decide for themselves whether to use it or not.
So, for starters, the subject of discussion. We will compare the creation of objects using the constructor-prototype bundle (i.e., all methods are stored in the prototype, all properties are created by the designer)
function make_obj(a, b) {
this.prop1 = a;
this.prop2 = b;
}
make_obj.prototype = {
method1: function(){...},
method2: function(){...},
methodN: ...
}
* This source code was highlighted with Source Code Highlighter.
( -, , , ).
function make_obj(a, b) {
var prop1 = a;
var prop2 = b;
method1 = function(){...}
method2 = function(){...}
methodN = ...
}
* This source code was highlighted with Source Code Highlighter.
«» «», .
( ) «» . , , , .
this (property = 5 this.property = 5, ).
.
- , , , , , - . , — , .
- JavaScript, JScript ECMA-262 «», . , — . , «» — , . — .
, . ( ) (.. ). , 1000 , 15 , «» , «». IE6 250 , IE7 — 110. 15.
100-200 , - (.. «» , , ).
, , . 3-4 , + 25-50 , .
50 — ( ).
- «» private , protected (.. , ) .
, .. , ( ).
- , this[(a > 2? 'max': 'min')]
, .
- . , , , - ( , ).
, .
- PHP5 , , private public, public protected — .
JS, this. .
, , , , , 100%, .
, «» ( - ), .
, - ( ) , , , , (, - ).