Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about the efficiency of closure/encapsulation in JavaScript

I'm somewhat new to JavaScript, so bear with me if this is a dumb question.

Let's say that I've got a "class" that looks like this:

var obj = function () {
    var val;
    return {
        setVal: function(newVal) {
            val = newVal;
        },
        getVal: function() {
            return val;
        }
    };
};

Assuming my syntax is correct, this defines a class with a "private" property named "value," with methods to set/get the property. Now, I will create two objects from this class:

var myObj = obj();
var yourObj = obj();

Does this create a separate setVal() and getVal() method for each object? If not, why not? If so, is this a serious concern when building efficient web applications? Is the trade-off (if any) of efficiency for closure worth it in most/all contexts? Am I dumb?

Thanks, Gerard

like image 259
GRardB Avatar asked Jun 13 '11 13:06

GRardB


1 Answers

var obj = function () {
    var val;
    return {
        setVal: function(newVal) {
            val = newVal;
        },
        getVal: function() {
            return val;
        }
    };
};

what this function does is as following :

  • create variable named val
  • create new object
  • create a new function and assign it to field setVal
  • create a new function and assign it to field getVal
  • return object.

So your always creating 4 new things.

This isn't really a problem if you have less then a 1000 objects on the page. Refactoring it away is a micro optimisation.

The alternative would be to not rely on local variables and use this._val to indicate that val is private.

like image 123
Raynos Avatar answered Nov 15 '22 05:11

Raynos