0

If I create custom objects through functions like this:

function createCustomObject ( state ) {
    let obj = { state };
    obj.doSomething = function ( ) {
        // do something
    };
    return obj;
}

let myNewObject = createCustomObject( { foo: 'bar' } );
myNewObject.doSomething();

How does that work out memory-wise? Does JavaScript keep a separate copy of the doSomething method for each of the objects I create? If I need to create thousands of objects will using prototypes/composition be more efficient?

ngr900
  • 452
  • 4
  • 12

1 Answers1

0

Yes, a new object will be created for each call.

function createCustomObject ( state ) {
  let obj = { state };
  obj.doSomething = function() {};
  return obj;
}
var o1 = createCustomObject();
var o2 = createCustomObject();
console.log(o1 === o2); // false
console.log(o1.doSomething === o2.doSomething); // false

If you want to share the methods, yes, better use prototypical inheritance.

function CustomObject ( state ) {
  this.state = state;
}
CustomObject.prototype.doSomething = function() {};
var o1 = new CustomObject();
var o2 = new CustomObject();
console.log(o1 === o2); // false
console.log(o1.doSomething === o2.doSomething); // true
Oriol
  • 274,082
  • 63
  • 437
  • 513