-1

I came across a piece of logic from a colleague and want to have clarity on the consequences before i submit a change. Basically, I have a class:

var MyClass = function(){};
MyClass.prototype = {...}

In another file, I am defining a module that requires that class and goes a little something like this:

return {
   propA: new MyClass().propA,
   propB: new MyClass().propB
};

The alternative way would be declaring a new MyClass object and use it like:

var myObject = new MyClass();

return {
   propA: myObject.propA,
   propB: myObject.propB
};

What would be the advantages and pitfalls of using each one of those?

André Alçada Padez
  • 10,987
  • 24
  • 67
  • 120
  • Those are two different things. You want `propA` and `propB` properties of the *same* object or different? – dfsq Jul 22 '14 at 09:34
  • they are both prototypal properties, so they are shared between objects – André Alçada Padez Jul 22 '14 at 09:37
  • 1
    Andre: a member/property that's declared on the prototype does not have to be the same for every instance. You can shadow that member for a particular instance and for that instance it'll be different. Shadowing is explained here: http://stackoverflow.com/a/16063711/1641941 As far as guarantee to have the prototype value; David's answer is what you should use. – HMR Jul 22 '14 at 13:56

2 Answers2

2

Since (as far as I can tell from the example) you're only instantiating MyClass to access the prototypical properties, why not cut-out the middle-man?

return {
   propA: MyClass.prototype.propA,
   propB: MyClass.prototype.propB
};
David
  • 391
  • 1
  • 3
1

It looks like the second method is more efficient because it create and uses only one instance, which takes less CPU time and less memory.

In your first example you create 2 new instances of MyClass and return 1 property from each one.

In the second, you create new instance of MyClass and store a reference to it in myObject.

UnTraDe
  • 3,747
  • 10
  • 36
  • 60