6

In Javascript, I can create a "class" like this:

var MyClass = function(){
    return this;
};

var myClassInstance = new MyClass();

What is the difference between doing the above and doing this:

var MyClass = {};

var myClassInstance = Object.create(MyClass);

Is there any reason to use one over the other?

eatonphil
  • 13,115
  • 27
  • 76
  • 133
  • 2
    Dupe of http://stackoverflow.com/questions/2709612/using-object-create-instead-of-new or http://stackoverflow.com/questions/4166616/understanding-the-difference-between-object-create-and-new-somefunction-in-j? – j08691 Oct 20 '14 at 17:18
  • it means you are dealing with objects .;) – Avinash Babu Oct 20 '14 at 17:18
  • 2
    You will see the difference if you put some initialization logic inside the constructor function. – Felix Kling Oct 20 '14 at 17:20
  • One reason is that when using the first style, using a function, `myClassInstance instanceof MyClass` returns true. – forgivenson Oct 20 '14 at 17:21
  • @forgivenson: As does `MyClass.isPrototypeOf(myClassInstance)` when using second style. But Felix is right, the second pattern "lacks" an initialisation *function* – Bergi Oct 20 '14 at 20:29

0 Answers0