Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between MyClass.prototype = new Object() and MyClass.prototype = Object

could anyone please tell me, where in Javascript the difference between

MyClass.prototype = new Object(); //or ... = {}

and

MyClass.prototype = Object;

is? And if there is no difference in the result, which one is the best-practise-way-to-go?

like image 970
moxn Avatar asked Sep 14 '09 06:09

moxn


1 Answers

Your first two examples are completely equivalent:

MyClass.prototype = new Object(); // empty object
MyClass.prototype = {}; // empty object

Your third example is not valid, since you are assigning to the MyClass.prototype a reference to the Object constructor, and it's a function, not a new object.

I personally prefer the second, the object literal or initialiser syntax:

MyClass.prototype = {prop1: 'value', prop2: 'value2'};
//...
MyClass.prototype.foo = 'bar';
MyClass.prototype.method1: function () {/**/};

Edit: In response to your comment, an empty object literal { } essentially equivalent to new Object() because of this:

The production ObjectLiteral : { } is evaluated as follows:

  1. Create a new object as if by the expression new Object().
  2. Return Result(1).

For more details check the 11.1.5 section (Object Initialiser) of the ECMAScript Language Spec (pdf).

Edit: The third example won't produce any errors, but is not good at all, for example you can easily clobber the Object constructor function if you extend afterward the MyClass.prototype:

MyClass.prototype = Object;
MyClass.prototype.foo = 'bar';

Object.foo === MyClass.prototype.foo; // true
like image 188
Christian C. Salvadó Avatar answered Sep 22 '22 12:09

Christian C. Salvadó