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
var obj = function () {
var val;
return {
setVal: function(newVal) {
val = newVal;
},
getVal: function() {
return val;
}
};
};
what this function does is as following :
val
setVal
getVal
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With