This is just a simple question. Either way works. I prefer my first example, but I didn’t know if doing it this way causes more memory to be allocated than the second example since we are calling “new” on the object….
Example 1
var post = function(){
var self = this;
self.div = $('<div></div>');
self.color = function(color){
this.div.css({background:color});
}
}
var p = new post();
p.color("#FFF");
Example 2
var post = function(){
self = this;
self.div = $('<div></div>');
}
var color = function(p, color){
p.div.css({background:color});
}
var p = new post();
color(p, "#FFF");
So, in the first example, the color function I believe will get recreated everytime a new post is called. What if I have a 100 new post(); calls. Is is less efficient than Example 2 where the function is only defined one time?
Does that make sense what I’m asking?
Yes, in Example 1 there will be a separate instance of the “color” function for every instance of a “post” object, whereas there will only be one instance of the function in Example 2. Clearly, if you plan to have a large number of “post” object instances then you are using more memory than you need to.
In JavaScript, the typical (or prototypical!) way of solving this problem using the best parts of your two examples is as follows (note that I am using “Post” with a capital “P”, per convention of constructor functions which are intended for use with the
newoperator):When looking for a property on an object (e.g. “p.color” in our examples), if the property isn’t defined directly on the instance then it is looked up as an attribute of the “
prototype” of the function which constructed the object (e.g. “Post.prototype.color”). This also means you can define instance methods on the prototype and override them by assigning new functions on individual instance property names directly, if you want.This way we still get the nice object-oriented syntax of calling “
p.color(...)” and the benefit of only one function method instance which is shared by all “Post” instances.