efficiency of anonymous function storage

anonymous-function, javascript, performance

Solution

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.

Problem

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!

Original source

Related problems