function Foo(strParm1, intParam2){ var param1 = strParm1; var param2 = intParm2; this.GetParam1 = function(){ return param1; } this.GetParam2 = function(){ return param2; } } 

Here is the question whether to create private members param1 and param2 as shown above, or you can do this:

 function Foo(strParm1, intParam2){ this.GetParam1 = function(){ return strParm1; } this.GetParam2 = function(){ return intParam2; } } 

What is the life of the parameters strParm1, intParam2 ???
thank!!!

    2 answers 2

    Whether or not the programmer decides, the life of the parameters depends on how "important" the object generated by the constructor is. Naturally, if an object is not used anywhere else and cannot be used with it, the garbage collector can distribute it (and not the fact that it will do it), but if it is no longer needed and you should not think about it.

    The second method has one big drawback - the getParam1 and getParam2 methods for each generated object are copied (read "different"), in fact this is the price of privacy in javascript, of course, if we are talking about, for example, singleton, simply using these approaches will not be.

    Personally, I advise you to use this approach only when it is really necessary. In general, it is much better to use prototypes. (just to avoid copying)

    To provide "pseudo-privacy" is usually used about the following approach:

     function Foo(a,b){ this._a = a; this._b = b; } Foo.prototype.getA = function() { return this._a; } Foo.prototype.getB = function() { return this._b; } 
    • how do i use prototype if param1 and param2 are private? private - they need a current to read. - Acne
    • that's the rub that true privacy can only be ensured by copying functions for each object locally. - Zowie
    • Ok, if I make the task presented in the question the second option, it will be the equivalent of the first option. and if the parameters are destroyed as they are used, it turns out that they are used in the heteras and will live as long as the object lives correctly? - Acne
    • True, but when using the prototype - we have common getters and setters for all objects, in the second example - each object has its own getters and setters , but then we provide true privacy **** There is no other way to implement true privacy in javascript - Zowie

    In your case, to create something extra is meaningless ...

    Function parameters (and these are ordinary local variables) - live forever (until the context is deleted, and in your situation - context = object)

    Private fields, IMHO, in JS - do not exist ...

    • So it is ... Yes, when creating "private" fields, in fact, just create different functions, but not private fields =) - Zowie