Justin Bull
Justin Bull

Reputation: 8215

Define constructor prototype with object literal

Which method below is best to define a constructor prototype and why?

Method 1:

MyConstructor.prototype.myFunction1 = function(){};
MyConstructor.prototype.myFunction2 = function(){};

Method 2:

MyConstructor.prototype = {
    myFunction1: function(){},
    myFunction2: function(){}
};

I'm mostly concerned about speed. Thanks!

Upvotes: 1

Views: 957

Answers (4)

You should use the method 1. Using the method 2, everytime you create a new instance, you will "re-create" the methods, since they are inside the constructor.

Upvotes: 0

ssohjiro
ssohjiro

Reputation: 72

Speaking further about the readability of your code,

method 1 is better than method 2.

Method 2 spend one more indentation. So it cause difficulty for reading codes.

Additionally, in my case, I can't inference that whether this function is prototype method or just static member function when we see a function name part in the lower part of codes.

Personally, in conclusion, I prefer method 2 if there not be much of a difference about performance.

Thanks!

Upvotes: -1

Sean McMillan
Sean McMillan

Reputation: 10093

var example = new MyConstructor();

under method 1:

example.constructor === MyConstructor;

under method 2:

typeof(example.constructor) === 'undefined';

The prototype object that comes with a function has a property constructor that points back to the function. If you assign to the proprties of that object, you keep the constructor property. If you overwrite the prototype property with a new object, you lose the constructor property.

The performance difference is minimal. Because constructor is so fragile, you can't really trust it, so I don't bother to preserve it.

Upvotes: 0

KooiInc
KooiInc

Reputation: 122898

I would say there wouldn't be much of a difference. Using an object literal to assign to the Object.prototype is something you can't do if you're assigning the prototype within the constructor (which can be usefull sometimes).

Maybe you should write a little performance test using jsperf.com.

Upvotes: 2

Related Questions