Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

efficiency of anonymous function storage

Suppose I create an object factory like so:

var newObj=function(x){
  var obj=[]
  obj.x=x
  obj.add=function(n){
    return this.x+n
  }
  return obj
}

Now suppose I create hundreds of instances of this object:

var obj1=newObj(1)
var obj2=newObj(2)
...

Does each obj1,obj2,... store their own copy of obj.add or do they all contain a reference to a single instance of obj.add stored in memory?

Thanks!

like image 993
gloo Avatar asked Jul 07 '13 15:07

gloo


2 Answers

Both obj and obj2 will instantiate their own copies of obj.add. They are function expressions that get executed at creation and stored in memory for the duration of the object's lifetime.

If you want to maintain performance, what you should use is prototyping:

var newObj=function(x){
  this.obj = [];
  this.obj.x = x;
  return this.obj;
}

newObj.prototype.add = function(n) {
    return this.obj.x += n;
}

This will create a function that all future newObj objects will use without taking up extra space in memory for the exact same function.

like image 151
Way Spurr-Chen Avatar answered Oct 20 '22 23:10

Way Spurr-Chen


They will all have their own instances of that method.

If you use prototypes, they will share that method, given you declare it on the prototype object.

So you could do something like

newObj.prototype.add = function(n) {
    return this.x+n
}

And then not declare add on the object as before.

In V8 there is a thing called hidden classes which basically means that all newObj instances will share a hidden class as long as you don't make changes to an instance, which would (as far as I understand) effectively make all the newObj's share the method as with prototyping.

like image 25
altschuler Avatar answered Oct 20 '22 23:10

altschuler