1

I usually extend constructor functions with the .prototype property, to have multiple instances reference the same code (instead of having several identical code), like this:

function Effect(){}
Effect.prototype.run = function(){}

However, due to the structure of my current project, I would like to do something like this:

Define effects object, with effect options:

var effects = {
    e1 : {
        run: function(){console.log(this);}
    },
    e2 : {
        run: function(){console.log(this);}
    }
}

Create Effect instance using the object definitions

function Effect(effect) {
    this.run = effect.run;    
}

Now I can create several instances (maybe hundreds)

var E1 = new Effect(effects.e1);
var E2 = new Effect(effects.e2);
var E3 = new Effect(effects.e2);
.....

However I'm concerned, if the .run functions will be defined multiple times.

Will these new instances reference the same function (defined in the effects object), or will they create a new 'local' function for each instance, using up memory space?

LongInt
  • 1,739
  • 2
  • 16
  • 29

1 Answers1

1

A function is an object, and as such it will always be stored by reference. Assigning it to a different variable or property will only create a new reference to the existing function object, and eat not more memory than needed for that variable or property.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • But according to this answer: http://stackoverflow.com/questions/8433459/js-why-use-prototype , the function is created on each instance. Just wondering if that is the case in my example. – LongInt Jan 31 '15 at 17:13
  • Because there, the *function expression is evaluated* on every constructor call, creating a new function object each time (and then assigning it to the respective instance). It's not the assignment that is responsible for this. – Bergi Jan 31 '15 at 17:17
  • Ahh, now it makes sense. Sometimes it's just about the right phrasing :) – LongInt Feb 01 '15 at 11:49