Understanding the difference between Object.create() and new SomeFunction()












350















I recently stumbled upon the Object.create() method in JavaScript, and am trying to deduce how it is different from creating a new instance of an object with new SomeFunction(), and when you would want to use one over the other.



Consider the following example:






var test = {
val: 1,
func: function() {
return this.val;
}
};
var testA = Object.create(test);

testA.val = 2;
console.log(test.func()); // 1
console.log(testA.func()); // 2

console.log('other test');
var otherTest = function() {
this.val = 1;
this.func = function() {
return this.val;
};
};

var otherTestA = new otherTest();
var otherTestB = new otherTest();
otherTestB.val = 2;
console.log(otherTestA.val); // 1
console.log(otherTestB.val); // 2

console.log(otherTestA.func()); // 1
console.log(otherTestB.func()); // 2





Notice that the same behaviour is observed in both cases. It seems to me that the primary differences between these two scenarios are:




  • The object used in Object.create() actually forms the prototype of the new object, whereas in the new Function() from the declared properties/functions do not form the prototype.

  • You cannot create closures with the Object.create() syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.


Are the above statements correct? And am I missing something? When would you use one over the other?



EDIT: link to jsfiddle version of above code sample: http://jsfiddle.net/rZfYL/










share|improve this question




















  • 2





    See also Using “Object.create” instead of “new”

    – Bergi
    Jul 24 '15 at 15:04
















350















I recently stumbled upon the Object.create() method in JavaScript, and am trying to deduce how it is different from creating a new instance of an object with new SomeFunction(), and when you would want to use one over the other.



Consider the following example:






var test = {
val: 1,
func: function() {
return this.val;
}
};
var testA = Object.create(test);

testA.val = 2;
console.log(test.func()); // 1
console.log(testA.func()); // 2

console.log('other test');
var otherTest = function() {
this.val = 1;
this.func = function() {
return this.val;
};
};

var otherTestA = new otherTest();
var otherTestB = new otherTest();
otherTestB.val = 2;
console.log(otherTestA.val); // 1
console.log(otherTestB.val); // 2

console.log(otherTestA.func()); // 1
console.log(otherTestB.func()); // 2





Notice that the same behaviour is observed in both cases. It seems to me that the primary differences between these two scenarios are:




  • The object used in Object.create() actually forms the prototype of the new object, whereas in the new Function() from the declared properties/functions do not form the prototype.

  • You cannot create closures with the Object.create() syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.


Are the above statements correct? And am I missing something? When would you use one over the other?



EDIT: link to jsfiddle version of above code sample: http://jsfiddle.net/rZfYL/










share|improve this question




















  • 2





    See also Using “Object.create” instead of “new”

    – Bergi
    Jul 24 '15 at 15:04














350












350








350


218






I recently stumbled upon the Object.create() method in JavaScript, and am trying to deduce how it is different from creating a new instance of an object with new SomeFunction(), and when you would want to use one over the other.



Consider the following example:






var test = {
val: 1,
func: function() {
return this.val;
}
};
var testA = Object.create(test);

testA.val = 2;
console.log(test.func()); // 1
console.log(testA.func()); // 2

console.log('other test');
var otherTest = function() {
this.val = 1;
this.func = function() {
return this.val;
};
};

var otherTestA = new otherTest();
var otherTestB = new otherTest();
otherTestB.val = 2;
console.log(otherTestA.val); // 1
console.log(otherTestB.val); // 2

console.log(otherTestA.func()); // 1
console.log(otherTestB.func()); // 2





Notice that the same behaviour is observed in both cases. It seems to me that the primary differences between these two scenarios are:




  • The object used in Object.create() actually forms the prototype of the new object, whereas in the new Function() from the declared properties/functions do not form the prototype.

  • You cannot create closures with the Object.create() syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.


Are the above statements correct? And am I missing something? When would you use one over the other?



EDIT: link to jsfiddle version of above code sample: http://jsfiddle.net/rZfYL/










share|improve this question
















I recently stumbled upon the Object.create() method in JavaScript, and am trying to deduce how it is different from creating a new instance of an object with new SomeFunction(), and when you would want to use one over the other.



Consider the following example:






var test = {
val: 1,
func: function() {
return this.val;
}
};
var testA = Object.create(test);

testA.val = 2;
console.log(test.func()); // 1
console.log(testA.func()); // 2

console.log('other test');
var otherTest = function() {
this.val = 1;
this.func = function() {
return this.val;
};
};

var otherTestA = new otherTest();
var otherTestB = new otherTest();
otherTestB.val = 2;
console.log(otherTestA.val); // 1
console.log(otherTestB.val); // 2

console.log(otherTestA.func()); // 1
console.log(otherTestB.func()); // 2





Notice that the same behaviour is observed in both cases. It seems to me that the primary differences between these two scenarios are:




  • The object used in Object.create() actually forms the prototype of the new object, whereas in the new Function() from the declared properties/functions do not form the prototype.

  • You cannot create closures with the Object.create() syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.


Are the above statements correct? And am I missing something? When would you use one over the other?



EDIT: link to jsfiddle version of above code sample: http://jsfiddle.net/rZfYL/






var test = {
val: 1,
func: function() {
return this.val;
}
};
var testA = Object.create(test);

testA.val = 2;
console.log(test.func()); // 1
console.log(testA.func()); // 2

console.log('other test');
var otherTest = function() {
this.val = 1;
this.func = function() {
return this.val;
};
};

var otherTestA = new otherTest();
var otherTestB = new otherTest();
otherTestB.val = 2;
console.log(otherTestA.val); // 1
console.log(otherTestB.val); // 2

console.log(otherTestA.func()); // 1
console.log(otherTestB.func()); // 2





var test = {
val: 1,
func: function() {
return this.val;
}
};
var testA = Object.create(test);

testA.val = 2;
console.log(test.func()); // 1
console.log(testA.func()); // 2

console.log('other test');
var otherTest = function() {
this.val = 1;
this.func = function() {
return this.val;
};
};

var otherTestA = new otherTest();
var otherTestB = new otherTest();
otherTestB.val = 2;
console.log(otherTestA.val); // 1
console.log(otherTestB.val); // 2

console.log(otherTestA.func()); // 1
console.log(otherTestB.func()); // 2






javascript prototype object-create






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 24 '17 at 18:45









BanksySan

11.2k1973143




11.2k1973143










asked Nov 12 '10 at 16:12









MattMatt

29.3k2596143




29.3k2596143








  • 2





    See also Using “Object.create” instead of “new”

    – Bergi
    Jul 24 '15 at 15:04














  • 2





    See also Using “Object.create” instead of “new”

    – Bergi
    Jul 24 '15 at 15:04








2




2





See also Using “Object.create” instead of “new”

– Bergi
Jul 24 '15 at 15:04





See also Using “Object.create” instead of “new”

– Bergi
Jul 24 '15 at 15:04












10 Answers
10






active

oldest

votes


















229















The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.




Yes, Object.create builds an object that inherits directly from the one passed as its first argument.



With constructor functions, the newly created object inherits from the constructor's prototype, e.g.:



var o = new SomeConstructor();


In the above example, o inherits directly from SomeConstructor.prototype.



There's a difference here, with Object.create you can create an object that doesn't inherit from anything, Object.create(null);, on the other hand, if you set SomeConstructor.prototype = null; the newly created object will inherit from Object.prototype.




You cannot create closures with the Object.create syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.




Well, you can create closures, e.g. using property descriptors argument:



var o = Object.create({inherited: 1}, {
foo: {
get: (function () { // a closure
var closured = 'foo';
return function () {
return closured+'bar';
};
})()
}
});

o.foo; // "foobar"


Note that I'm talking about the ECMAScript 5th Edition Object.create method, not the Crockford's shim.



The method is starting to be natively implemented on latest browsers, check this compatibility table.






share|improve this answer





















  • 2





    @CMS 2 questions. 1) Does the scope chain on Object.create(null) still terminate at the global scope (such as 'window' in a browser), or does it terminate on itself? 2) It is still not clear to me why Object.create was introduced (e.g. what feature was missing that this addressed?) and why one would use it instead of new Function();

    – Matt
    Nov 12 '10 at 16:30






  • 9





    @Matt, 1) the scope chain is not really a related concept here, scope chain is related to identifier resolution, e.g.: how foo; is resolved in the current lexical environment. 2) To provide an easy way to implement inheritance, it's a really powerful construct. IMO I would use it because it's really simple and lightweight, but for production code, we still need to wait some time until ES5 is supported widely. About missing features, the fact of creating a "pristine" object, Object.create(null); was missing, it's really useful to implement reliable hash-table-like objects...

    – CMS
    Nov 12 '10 at 16:38











  • @CMS Thank you!

    – Matt
    Nov 12 '10 at 17:27






  • 1





    You're welcome @Matt :)

    – CMS
    Nov 12 '10 at 20:25











  • @CMS Thanks. So simply when you create a object by using 'Object.create',you get the ability to select the object that should be its prototype.

    – Anshul
    Sep 2 '14 at 18:52



















358














Very simply said, new X is Object.create(X.prototype) with additionally running the constructor function. (And giving the constructor the chance to return the actual object that should be the result of the expression instead of this.)



That’s it. :)



The rest of the answers are just confusing, because apparently nobody else reads the definition of new either. ;)






share|improve this answer





















  • 21





    +1 Simplicity and clarity! (Though the Object.create(null) seems a nice option - maybe should mention that).

    – user949300
    Sep 3 '14 at 4:15











  • keep it simple that's the way to go

    – Bruce
    May 26 '16 at 12:12











  • That just leaves the question of "wait, so functions have prototypes too? What's the relationship between those and object prototypes?"

    – Qwertie
    May 31 '16 at 22:46






  • 2





    @Qwertie: In JS, everything is an object. :) They copied that from Java, who copied it from SmallTalk, who went all the way to the end with it. It’s a nice case of “emergence”, making life easier in general.

    – Evi1M4chine
    Jun 30 '16 at 14:54











  • @Evi1M4chine actually in Java, functions are not objects (and neither are primitives, for that matter)... and objects don't have prototypes, so the comparison seems un-fitting. The fact that JS works differently than other popular OO languages is a major source of confusion (and it doesn't help that browsers don't provide an easy way to visualize the network of objects including functions and prototypes). P.S. I found this link helpful : davidwalsh.name/javascript-objects-deconstruction

    – Qwertie
    Jul 2 '16 at 4:27





















188














Here are the steps that happen internally for both calls:

(Hint: the only difference is in step 3)





new Test():




  1. create new Object() obj

  2. set obj.__proto__ to Test.prototype

  3. return Test.call(obj) || obj;
    // normally obj is returned but constructors in JS can return a value




Object.create( Test.prototype )




  1. create new Object() obj

  2. set obj.__proto__ to Test.prototype

  3. return obj;




So basically Object.create doesn't execute the constructor.






share|improve this answer


























  • @Ray so using object.create we font have the properties of function mentioned in constructor function?

    – user2156081
    Feb 21 '17 at 12:28











  • @sortednoun as long as the properties are private and not specified on the prototype, yes, they won't be inherited and you won't have them in the new object (and, I would add, you can expect to get eventual prototyped properties from the parent, just when the parent constructor has been execute at least once).

    – Kamafeather
    Jul 25 '17 at 16:52



















59














Let me try to explain (more on Blog) :




  1. When you write Car constructor var Car = function(){}, this is how things are internally:
    A diagram of prototypal chains when creating javascript objects
    We have one {prototype} hidden link to Function.prototype which is not accessible and one prototype link to Car.prototype which is accessible and has an actual constructor of Car. Both Function.prototype and Car.prototype have hidden links to Object.prototype.


  2. When we want to create two equivalent objects by using the new operator and create method then we have to do it like this: Honda = new Car(); and Maruti = Object.create(Car.prototype).A diagram of prototypal chains for differing object creation methods
    What is happening?



    Honda = new Car(); — When you create an object like this then hidden {prototype} property is pointed to Car.prototype. So here, the {prototype} of the Honda object will always be Car.prototype — we don't have any option to change the {prototype} property of the object. What if I want to change the prototype of our newly created object?
    Maruti = Object.create(Car.prototype) — When you create an object like this you have an extra option to choose your object's {prototype} property. If you want Car.prototype as the {prototype} then pass it as a parameter in the function. If you don't want any {prototype} for your object then you can pass null like this: Maruti = Object.create(null).




Conclusion — By using the method Object.create you have the freedom to choose your object {prototype} property. In new Car();, you don't have that freedom.



Preferred way in OO JavaScript :



Suppose we have two objects a and b.



var a = new Object();
var b = new Object();


Now, suppose a has some methods which b also wants to access. For that, we require object inheritance (a should be the prototype of b only if we want access to those methods). If we check the prototypes of a and b then we will find out that they share the prototype Object.prototype.



Object.prototype.isPrototypeOf(b); //true
a.isPrototypeOf(b); //false (the problem comes into the picture here).


Problem — we want object a as the prototype of b, but here we created object b with the prototype Object.prototype.
Solution — ECMAScript 5 introduced Object.create(), to achieve such inheritance easily. If we create object b like this:



var b = Object.create(a);


then,



a.isPrototypeOf(b);// true (problem solved, you included object a in the prototype chain of object b.)


So, if you are doing object oriented scripting then Object.create() is very useful for inheritance.






share|improve this answer


























  • So, it is somewhat similar to object creation without constructor invocation? We will enjoy all the benefits of the class. The obj instanceof Class will also be true. But we are not invoking the Class function via new.

    – Praveen
    Mar 30 '16 at 8:49











  • @Anshul You said that a.isPrototypeOf(b); will return false which is right, because both Objects are different and pointing to different memory. The correct way to do this with the new operator is here. - jsfiddle.net/167onunp .

    – Sagar Karira
    Nov 10 '16 at 11:29













  • Why wouldn't you just set the prototype property of b to a, instead of doing this?

    – Amnestic
    Dec 3 '16 at 19:09











  • Liked the article on your blog too. Helped me understand the concept much better. Thank you.

    – steady_daddy
    Aug 9 '17 at 9:59











  • The conclusion says it all.

    – kushalvm
    Aug 14 '17 at 11:20



















37














This:



var foo = new Foo();


and



var foo = Object.create(Foo.prototype);


are quite similar. One important difference is that new Foo actually runs constructor code, whereas Object.create will not execute code such as



function Foo() {
alert("This constructor does not run with Object.create");
}


Note that if you use the two-parameter version of Object.create() then you can do much more powerful things.






share|improve this answer



















  • 1





    Great explanation. Might I add, using Object.create in its simplest form like this allows you to omit constructor functions from your code while taking advantage of prototype inheritance.

    – Ricky Boyce
    Nov 19 '15 at 4:38





















21














The difference is the so-called "pseudoclassical vs. prototypal inheritance". The suggestion is to use only one type in your code, not mixing the two.



In pseudoclassical inheritance (with "new" operator), imagine that you first define a pseudo-class, and then create objects from that class. For example, define a pseudo-class "Person", and then create "Alice" and "Bob" from "Person".



In prototypal inheritance (using Object.create), you directly create a specific person "Alice", and then create another person "Bob" using "Alice" as a prototype. There is no "class" here; all are objects.



Internally, JavaScript uses "prototypal inheritance"; the "pseudoclassical" way is just some sugar.



See this link for a comparison of the two ways.






share|improve this answer































    20














    function Test(){
    this.prop1 = 'prop1';
    this.prop2 = 'prop2';
    this.func1 = function(){
    return this.prop1 + this.prop2;
    }
    };

    Test.prototype.protoProp1 = 'protoProp1';
    Test.prototype.protoProp2 = 'protoProp2';
    var newKeywordTest = new Test();
    var objectCreateTest = Object.create(Test.prototype);

    /* Object.create */
    console.log(objectCreateTest.prop1); // undefined
    console.log(objectCreateTest.protoProp1); // protoProp1
    console.log(objectCreateTest.__proto__.protoProp1); // protoProp1

    /* new */
    console.log(newKeywordTest.prop1); // prop1
    console.log(newKeywordTest.__proto__.protoProp1); // protoProp1


    Summary:



    1) with new keyword there are two things to note;



    a) function is used as a constructor



    b) function.prototype object is passed to the __proto__ property ... or where __proto__ is not supported, it is the second place where the new object looks to find properties



    2) with Object.create(obj.prototype) you are constructing an object (obj.prototype) and passing it to the intended object ..with the difference that now new object's __proto__ is also pointing to obj.prototype (please ref ans by xj9 for that)






    share|improve this answer

































      10














      Internally Object.create does this:



      Object.create = function (o) {
      function F() {}
      F.prototype = o;
      return new F();
      };


      The syntax just takes away the illusion that JavaScript uses Classical Inheritance.






      share|improve this answer



















      • 24





        The ECMAScript 5 Object.create method, does a lot more than that, you can define properties by property descriptors and you can create an object that doesn't inherit from anything (Object.create(null);), this type of shims should be avoided because you can't really emulate that behavior on ES3. More info

        – CMS
        Nov 12 '10 at 16:24













      • Hmm, did not know.

        – xj9
        Nov 12 '10 at 19:25











      • Agree with @CMS but in general, it is simple polyfill for Object.create.

        – Vladimir Kovpak
        Jul 27 '17 at 21:02



















      9














      Accordingly to this answer and to this video new keyword does next things:




      1. Creates new object.


      2. Links new object to constructor function (prototype).


      3. Makes this variable point to the new object.


      4. Executes constructor function using the new object and implicit perform return this;


      5. Assigns constructor function name to new object's property constructor.



      Object.create performs only 1st and 2nd steps!!!






      share|improve this answer































        6














        Object creation variants.





        Variant 1 : 'new Object()' -> Object constructor without arguments.



        var p1 = new Object(); // 'new Object()' create and return empty object -> {}

        var p2 = new Object(); // 'new Object()' create and return empty object -> {}

        console.log(p1); // empty object -> {}

        console.log(p2); // empty object -> {}

        // p1 and p2 are pointers to different objects
        console.log(p1 === p2); // false

        console.log(p1.prototype); // undefined

        // empty object which is in fact Object.prototype
        console.log(p1.__proto__); // {}

        // empty object to which p1.__proto__ points
        console.log(Object.prototype); // {}

        console.log(p1.__proto__ === Object.prototype); // true

        // null, which is in fact Object.prototype.__proto__
        console.log(p1.__proto__.__proto__); // null

        console.log(Object.prototype.__proto__); // null


        enter image description here





        Variant 2 : 'new Object(person)' -> Object constructor with argument.



        const person = {
        name: 'no name',
        lastName: 'no lastName',
        age: -1
        }

        // 'new Object(person)' return 'person', which is pointer to the object ->
        // -> { name: 'no name', lastName: 'no lastName', age: -1 }
        var p1 = new Object(person);

        // 'new Object(person)' return 'person', which is pointer to the object ->
        // -> { name: 'no name', lastName: 'no lastName', age: -1 }
        var p2 = new Object(person);

        // person, p1 and p2 are pointers to the same object
        console.log(p1 === p2); // true
        console.log(p1 === person); // true
        console.log(p2 === person); // true

        p1.name = 'John'; // change 'name' by 'p1'
        p2.lastName = 'Doe'; // change 'lastName' by 'p2'
        person.age = 25; // change 'age' by 'person'

        // when print 'p1', 'p2' and 'person', it's the same result,
        // because the object they points is the same
        console.log(p1); // { name: 'John', lastName: 'Doe', age: 25 }
        console.log(p2); // { name: 'John', lastName: 'Doe', age: 25 }
        console.log(person); // { name: 'John', lastName: 'Doe', age: 25 }


        enter image description here





        Variant 3.1 : 'Object.create(person)'. Use Object.create with simple object 'person'. 'Object.create(person)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'person'.



        const person = {
        name: 'no name',
        lastName: 'no lastName',
        age: -1,
        getInfo: function getName() {
        return `${this.name} ${this.lastName}, ${this.age}!`;
        }
        }

        var p1 = Object.create(person);

        var p2 = Object.create(person);

        // 'p1.__proto__' and 'p2.__proto__' points to
        // the same object -> 'person'
        // { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
        console.log(p1.__proto__);
        console.log(p2.__proto__);
        console.log(p1.__proto__ === p2.__proto__); // true

        console.log(person.__proto__); // {}(which is the Object.prototype)

        // 'person', 'p1' and 'p2' are different
        console.log(p1 === person); // false
        console.log(p1 === p2); // false
        console.log(p2 === person); // false

        // { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
        console.log(person);

        console.log(p1); // empty object - {}

        console.log(p2); // empty object - {}

        // add properties to object 'p1'
        // (properties with the same names like in object 'person')
        p1.name = 'John';
        p1.lastName = 'Doe';
        p1.age = 25;

        // add properties to object 'p2'
        // (properties with the same names like in object 'person')
        p2.name = 'Tom';
        p2.lastName = 'Harrison';
        p2.age = 38;

        // { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
        console.log(person);

        // { name: 'John', lastName: 'Doe', age: 25 }
        console.log(p1);

        // { name: 'Tom', lastName: 'Harrison', age: 38 }
        console.log(p2);

        // use by '__proto__'(link from 'p1' to 'person'),
        // person's function 'getInfo'
        console.log(p1.getInfo()); // John Doe, 25!

        // use by '__proto__'(link from 'p2' to 'person'),
        // person's function 'getInfo'
        console.log(p2.getInfo()); // Tom Harrison, 38!


        enter image description here





        Variant 3.2 : 'Object.create(Object.prototype)'. Use Object.create with built-in object -> 'Object.prototype'. 'Object.create(Object.prototype)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'Object.prototype'.



        // 'Object.create(Object.prototype)' :
        // 1. create and return empty object -> {}.
        // 2. add to 'p1' property '__proto__', which is link to 'Object.prototype'
        var p1 = Object.create(Object.prototype);

        // 'Object.create(Object.prototype)' :
        // 1. create and return empty object -> {}.
        // 2. add to 'p2' property '__proto__', which is link to 'Object.prototype'
        var p2 = Object.create(Object.prototype);

        console.log(p1); // {}

        console.log(p2); // {}

        console.log(p1 === p2); // false

        console.log(p1.prototype); // undefined

        console.log(p2.prototype); // undefined

        console.log(p1.__proto__ === Object.prototype); // true

        console.log(p2.__proto__ === Object.prototype); // true


        enter image description here





        Variant 4 : 'new SomeFunction()'



        // 'this' in constructor-function 'Person'
        // represents a new instace,
        // that will be created by 'new Person(...)'
        // and returned implicitly
        function Person(name, lastName, age) {

        this.name = name;
        this.lastName = lastName;
        this.age = age;

        //-----------------------------------------------------------------
        // !--- only for demonstration ---
        // if add function 'getInfo' into
        // constructor-function 'Person',
        // then all instances will have a copy of the function 'getInfo'!
        //
        // this.getInfo: function getInfo() {
        // return this.name + " " + this.lastName + ", " + this.age + "!";
        // }
        //-----------------------------------------------------------------
        }

        // 'Person.prototype' is an empty object
        // (before add function 'getInfo')
        console.log(Person.prototype); // Person {}

        // With 'getInfo' added to 'Person.prototype',
        // instances by their properties '__proto__',
        // will have access to the function 'getInfo'.
        // With this approach, instances not need
        // a copy of the function 'getInfo' for every instance.
        Person.prototype.getInfo = function getInfo() {
        return this.name + " " + this.lastName + ", " + this.age + "!";
        }

        // after function 'getInfo' is added to 'Person.prototype'
        console.log(Person.prototype); // Person { getInfo: [Function: getInfo] }

        // create instance 'p1'
        var p1 = new Person('John', 'Doe', 25);

        // create instance 'p2'
        var p2 = new Person('Tom', 'Harrison', 38);

        // Person { name: 'John', lastName: 'Doe', age: 25 }
        console.log(p1);

        // Person { name: 'Tom', lastName: 'Harrison', age: 38 }
        console.log(p2);

        // 'p1.__proto__' points to 'Person.prototype'
        console.log(p1.__proto__); // Person { getInfo: [Function: getInfo] }

        // 'p2.__proto__' points to 'Person.prototype'
        console.log(p2.__proto__); // Person { getInfo: [Function: getInfo] }

        console.log(p1.__proto__ === p2.__proto__); // true

        // 'p1' and 'p2' points to different objects(instaces of 'Person')
        console.log(p1 === p2); // false

        // 'p1' by its property '__proto__' reaches 'Person.prototype.getInfo'
        // and use 'getInfo' with 'p1'-instance's data
        console.log(p1.getInfo()); // John Doe, 25!

        // 'p2' by its property '__proto__' reaches 'Person.prototype.getInfo'
        // and use 'getInfo' with 'p2'-instance's data
        console.log(p2.getInfo()); // Tom Harrison, 38!


        enter image description here






        share|improve this answer

























          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4166616%2funderstanding-the-difference-between-object-create-and-new-somefunction%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          10 Answers
          10






          active

          oldest

          votes








          10 Answers
          10






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          229















          The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.




          Yes, Object.create builds an object that inherits directly from the one passed as its first argument.



          With constructor functions, the newly created object inherits from the constructor's prototype, e.g.:



          var o = new SomeConstructor();


          In the above example, o inherits directly from SomeConstructor.prototype.



          There's a difference here, with Object.create you can create an object that doesn't inherit from anything, Object.create(null);, on the other hand, if you set SomeConstructor.prototype = null; the newly created object will inherit from Object.prototype.




          You cannot create closures with the Object.create syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.




          Well, you can create closures, e.g. using property descriptors argument:



          var o = Object.create({inherited: 1}, {
          foo: {
          get: (function () { // a closure
          var closured = 'foo';
          return function () {
          return closured+'bar';
          };
          })()
          }
          });

          o.foo; // "foobar"


          Note that I'm talking about the ECMAScript 5th Edition Object.create method, not the Crockford's shim.



          The method is starting to be natively implemented on latest browsers, check this compatibility table.






          share|improve this answer





















          • 2





            @CMS 2 questions. 1) Does the scope chain on Object.create(null) still terminate at the global scope (such as 'window' in a browser), or does it terminate on itself? 2) It is still not clear to me why Object.create was introduced (e.g. what feature was missing that this addressed?) and why one would use it instead of new Function();

            – Matt
            Nov 12 '10 at 16:30






          • 9





            @Matt, 1) the scope chain is not really a related concept here, scope chain is related to identifier resolution, e.g.: how foo; is resolved in the current lexical environment. 2) To provide an easy way to implement inheritance, it's a really powerful construct. IMO I would use it because it's really simple and lightweight, but for production code, we still need to wait some time until ES5 is supported widely. About missing features, the fact of creating a "pristine" object, Object.create(null); was missing, it's really useful to implement reliable hash-table-like objects...

            – CMS
            Nov 12 '10 at 16:38











          • @CMS Thank you!

            – Matt
            Nov 12 '10 at 17:27






          • 1





            You're welcome @Matt :)

            – CMS
            Nov 12 '10 at 20:25











          • @CMS Thanks. So simply when you create a object by using 'Object.create',you get the ability to select the object that should be its prototype.

            – Anshul
            Sep 2 '14 at 18:52
















          229















          The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.




          Yes, Object.create builds an object that inherits directly from the one passed as its first argument.



          With constructor functions, the newly created object inherits from the constructor's prototype, e.g.:



          var o = new SomeConstructor();


          In the above example, o inherits directly from SomeConstructor.prototype.



          There's a difference here, with Object.create you can create an object that doesn't inherit from anything, Object.create(null);, on the other hand, if you set SomeConstructor.prototype = null; the newly created object will inherit from Object.prototype.




          You cannot create closures with the Object.create syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.




          Well, you can create closures, e.g. using property descriptors argument:



          var o = Object.create({inherited: 1}, {
          foo: {
          get: (function () { // a closure
          var closured = 'foo';
          return function () {
          return closured+'bar';
          };
          })()
          }
          });

          o.foo; // "foobar"


          Note that I'm talking about the ECMAScript 5th Edition Object.create method, not the Crockford's shim.



          The method is starting to be natively implemented on latest browsers, check this compatibility table.






          share|improve this answer





















          • 2





            @CMS 2 questions. 1) Does the scope chain on Object.create(null) still terminate at the global scope (such as 'window' in a browser), or does it terminate on itself? 2) It is still not clear to me why Object.create was introduced (e.g. what feature was missing that this addressed?) and why one would use it instead of new Function();

            – Matt
            Nov 12 '10 at 16:30






          • 9





            @Matt, 1) the scope chain is not really a related concept here, scope chain is related to identifier resolution, e.g.: how foo; is resolved in the current lexical environment. 2) To provide an easy way to implement inheritance, it's a really powerful construct. IMO I would use it because it's really simple and lightweight, but for production code, we still need to wait some time until ES5 is supported widely. About missing features, the fact of creating a "pristine" object, Object.create(null); was missing, it's really useful to implement reliable hash-table-like objects...

            – CMS
            Nov 12 '10 at 16:38











          • @CMS Thank you!

            – Matt
            Nov 12 '10 at 17:27






          • 1





            You're welcome @Matt :)

            – CMS
            Nov 12 '10 at 20:25











          • @CMS Thanks. So simply when you create a object by using 'Object.create',you get the ability to select the object that should be its prototype.

            – Anshul
            Sep 2 '14 at 18:52














          229












          229








          229








          The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.




          Yes, Object.create builds an object that inherits directly from the one passed as its first argument.



          With constructor functions, the newly created object inherits from the constructor's prototype, e.g.:



          var o = new SomeConstructor();


          In the above example, o inherits directly from SomeConstructor.prototype.



          There's a difference here, with Object.create you can create an object that doesn't inherit from anything, Object.create(null);, on the other hand, if you set SomeConstructor.prototype = null; the newly created object will inherit from Object.prototype.




          You cannot create closures with the Object.create syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.




          Well, you can create closures, e.g. using property descriptors argument:



          var o = Object.create({inherited: 1}, {
          foo: {
          get: (function () { // a closure
          var closured = 'foo';
          return function () {
          return closured+'bar';
          };
          })()
          }
          });

          o.foo; // "foobar"


          Note that I'm talking about the ECMAScript 5th Edition Object.create method, not the Crockford's shim.



          The method is starting to be natively implemented on latest browsers, check this compatibility table.






          share|improve this answer
















          The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.




          Yes, Object.create builds an object that inherits directly from the one passed as its first argument.



          With constructor functions, the newly created object inherits from the constructor's prototype, e.g.:



          var o = new SomeConstructor();


          In the above example, o inherits directly from SomeConstructor.prototype.



          There's a difference here, with Object.create you can create an object that doesn't inherit from anything, Object.create(null);, on the other hand, if you set SomeConstructor.prototype = null; the newly created object will inherit from Object.prototype.




          You cannot create closures with the Object.create syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript.




          Well, you can create closures, e.g. using property descriptors argument:



          var o = Object.create({inherited: 1}, {
          foo: {
          get: (function () { // a closure
          var closured = 'foo';
          return function () {
          return closured+'bar';
          };
          })()
          }
          });

          o.foo; // "foobar"


          Note that I'm talking about the ECMAScript 5th Edition Object.create method, not the Crockford's shim.



          The method is starting to be natively implemented on latest browsers, check this compatibility table.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Oct 12 '18 at 10:48









          jithinkmatthew

          347311




          347311










          answered Nov 12 '10 at 16:22









          CMSCMS

          598k162846813




          598k162846813








          • 2





            @CMS 2 questions. 1) Does the scope chain on Object.create(null) still terminate at the global scope (such as 'window' in a browser), or does it terminate on itself? 2) It is still not clear to me why Object.create was introduced (e.g. what feature was missing that this addressed?) and why one would use it instead of new Function();

            – Matt
            Nov 12 '10 at 16:30






          • 9





            @Matt, 1) the scope chain is not really a related concept here, scope chain is related to identifier resolution, e.g.: how foo; is resolved in the current lexical environment. 2) To provide an easy way to implement inheritance, it's a really powerful construct. IMO I would use it because it's really simple and lightweight, but for production code, we still need to wait some time until ES5 is supported widely. About missing features, the fact of creating a "pristine" object, Object.create(null); was missing, it's really useful to implement reliable hash-table-like objects...

            – CMS
            Nov 12 '10 at 16:38











          • @CMS Thank you!

            – Matt
            Nov 12 '10 at 17:27






          • 1





            You're welcome @Matt :)

            – CMS
            Nov 12 '10 at 20:25











          • @CMS Thanks. So simply when you create a object by using 'Object.create',you get the ability to select the object that should be its prototype.

            – Anshul
            Sep 2 '14 at 18:52














          • 2





            @CMS 2 questions. 1) Does the scope chain on Object.create(null) still terminate at the global scope (such as 'window' in a browser), or does it terminate on itself? 2) It is still not clear to me why Object.create was introduced (e.g. what feature was missing that this addressed?) and why one would use it instead of new Function();

            – Matt
            Nov 12 '10 at 16:30






          • 9





            @Matt, 1) the scope chain is not really a related concept here, scope chain is related to identifier resolution, e.g.: how foo; is resolved in the current lexical environment. 2) To provide an easy way to implement inheritance, it's a really powerful construct. IMO I would use it because it's really simple and lightweight, but for production code, we still need to wait some time until ES5 is supported widely. About missing features, the fact of creating a "pristine" object, Object.create(null); was missing, it's really useful to implement reliable hash-table-like objects...

            – CMS
            Nov 12 '10 at 16:38











          • @CMS Thank you!

            – Matt
            Nov 12 '10 at 17:27






          • 1





            You're welcome @Matt :)

            – CMS
            Nov 12 '10 at 20:25











          • @CMS Thanks. So simply when you create a object by using 'Object.create',you get the ability to select the object that should be its prototype.

            – Anshul
            Sep 2 '14 at 18:52








          2




          2





          @CMS 2 questions. 1) Does the scope chain on Object.create(null) still terminate at the global scope (such as 'window' in a browser), or does it terminate on itself? 2) It is still not clear to me why Object.create was introduced (e.g. what feature was missing that this addressed?) and why one would use it instead of new Function();

          – Matt
          Nov 12 '10 at 16:30





          @CMS 2 questions. 1) Does the scope chain on Object.create(null) still terminate at the global scope (such as 'window' in a browser), or does it terminate on itself? 2) It is still not clear to me why Object.create was introduced (e.g. what feature was missing that this addressed?) and why one would use it instead of new Function();

          – Matt
          Nov 12 '10 at 16:30




          9




          9





          @Matt, 1) the scope chain is not really a related concept here, scope chain is related to identifier resolution, e.g.: how foo; is resolved in the current lexical environment. 2) To provide an easy way to implement inheritance, it's a really powerful construct. IMO I would use it because it's really simple and lightweight, but for production code, we still need to wait some time until ES5 is supported widely. About missing features, the fact of creating a "pristine" object, Object.create(null); was missing, it's really useful to implement reliable hash-table-like objects...

          – CMS
          Nov 12 '10 at 16:38





          @Matt, 1) the scope chain is not really a related concept here, scope chain is related to identifier resolution, e.g.: how foo; is resolved in the current lexical environment. 2) To provide an easy way to implement inheritance, it's a really powerful construct. IMO I would use it because it's really simple and lightweight, but for production code, we still need to wait some time until ES5 is supported widely. About missing features, the fact of creating a "pristine" object, Object.create(null); was missing, it's really useful to implement reliable hash-table-like objects...

          – CMS
          Nov 12 '10 at 16:38













          @CMS Thank you!

          – Matt
          Nov 12 '10 at 17:27





          @CMS Thank you!

          – Matt
          Nov 12 '10 at 17:27




          1




          1





          You're welcome @Matt :)

          – CMS
          Nov 12 '10 at 20:25





          You're welcome @Matt :)

          – CMS
          Nov 12 '10 at 20:25













          @CMS Thanks. So simply when you create a object by using 'Object.create',you get the ability to select the object that should be its prototype.

          – Anshul
          Sep 2 '14 at 18:52





          @CMS Thanks. So simply when you create a object by using 'Object.create',you get the ability to select the object that should be its prototype.

          – Anshul
          Sep 2 '14 at 18:52













          358














          Very simply said, new X is Object.create(X.prototype) with additionally running the constructor function. (And giving the constructor the chance to return the actual object that should be the result of the expression instead of this.)



          That’s it. :)



          The rest of the answers are just confusing, because apparently nobody else reads the definition of new either. ;)






          share|improve this answer





















          • 21





            +1 Simplicity and clarity! (Though the Object.create(null) seems a nice option - maybe should mention that).

            – user949300
            Sep 3 '14 at 4:15











          • keep it simple that's the way to go

            – Bruce
            May 26 '16 at 12:12











          • That just leaves the question of "wait, so functions have prototypes too? What's the relationship between those and object prototypes?"

            – Qwertie
            May 31 '16 at 22:46






          • 2





            @Qwertie: In JS, everything is an object. :) They copied that from Java, who copied it from SmallTalk, who went all the way to the end with it. It’s a nice case of “emergence”, making life easier in general.

            – Evi1M4chine
            Jun 30 '16 at 14:54











          • @Evi1M4chine actually in Java, functions are not objects (and neither are primitives, for that matter)... and objects don't have prototypes, so the comparison seems un-fitting. The fact that JS works differently than other popular OO languages is a major source of confusion (and it doesn't help that browsers don't provide an easy way to visualize the network of objects including functions and prototypes). P.S. I found this link helpful : davidwalsh.name/javascript-objects-deconstruction

            – Qwertie
            Jul 2 '16 at 4:27


















          358














          Very simply said, new X is Object.create(X.prototype) with additionally running the constructor function. (And giving the constructor the chance to return the actual object that should be the result of the expression instead of this.)



          That’s it. :)



          The rest of the answers are just confusing, because apparently nobody else reads the definition of new either. ;)






          share|improve this answer





















          • 21





            +1 Simplicity and clarity! (Though the Object.create(null) seems a nice option - maybe should mention that).

            – user949300
            Sep 3 '14 at 4:15











          • keep it simple that's the way to go

            – Bruce
            May 26 '16 at 12:12











          • That just leaves the question of "wait, so functions have prototypes too? What's the relationship between those and object prototypes?"

            – Qwertie
            May 31 '16 at 22:46






          • 2





            @Qwertie: In JS, everything is an object. :) They copied that from Java, who copied it from SmallTalk, who went all the way to the end with it. It’s a nice case of “emergence”, making life easier in general.

            – Evi1M4chine
            Jun 30 '16 at 14:54











          • @Evi1M4chine actually in Java, functions are not objects (and neither are primitives, for that matter)... and objects don't have prototypes, so the comparison seems un-fitting. The fact that JS works differently than other popular OO languages is a major source of confusion (and it doesn't help that browsers don't provide an easy way to visualize the network of objects including functions and prototypes). P.S. I found this link helpful : davidwalsh.name/javascript-objects-deconstruction

            – Qwertie
            Jul 2 '16 at 4:27
















          358












          358








          358







          Very simply said, new X is Object.create(X.prototype) with additionally running the constructor function. (And giving the constructor the chance to return the actual object that should be the result of the expression instead of this.)



          That’s it. :)



          The rest of the answers are just confusing, because apparently nobody else reads the definition of new either. ;)






          share|improve this answer















          Very simply said, new X is Object.create(X.prototype) with additionally running the constructor function. (And giving the constructor the chance to return the actual object that should be the result of the expression instead of this.)



          That’s it. :)



          The rest of the answers are just confusing, because apparently nobody else reads the definition of new either. ;)







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 27 '18 at 19:09









          Lyubomir

          11.7k33245




          11.7k33245










          answered Jul 30 '13 at 16:12









          Evi1M4chineEvi1M4chine

          4,82611813




          4,82611813








          • 21





            +1 Simplicity and clarity! (Though the Object.create(null) seems a nice option - maybe should mention that).

            – user949300
            Sep 3 '14 at 4:15











          • keep it simple that's the way to go

            – Bruce
            May 26 '16 at 12:12











          • That just leaves the question of "wait, so functions have prototypes too? What's the relationship between those and object prototypes?"

            – Qwertie
            May 31 '16 at 22:46






          • 2





            @Qwertie: In JS, everything is an object. :) They copied that from Java, who copied it from SmallTalk, who went all the way to the end with it. It’s a nice case of “emergence”, making life easier in general.

            – Evi1M4chine
            Jun 30 '16 at 14:54











          • @Evi1M4chine actually in Java, functions are not objects (and neither are primitives, for that matter)... and objects don't have prototypes, so the comparison seems un-fitting. The fact that JS works differently than other popular OO languages is a major source of confusion (and it doesn't help that browsers don't provide an easy way to visualize the network of objects including functions and prototypes). P.S. I found this link helpful : davidwalsh.name/javascript-objects-deconstruction

            – Qwertie
            Jul 2 '16 at 4:27
















          • 21





            +1 Simplicity and clarity! (Though the Object.create(null) seems a nice option - maybe should mention that).

            – user949300
            Sep 3 '14 at 4:15











          • keep it simple that's the way to go

            – Bruce
            May 26 '16 at 12:12











          • That just leaves the question of "wait, so functions have prototypes too? What's the relationship between those and object prototypes?"

            – Qwertie
            May 31 '16 at 22:46






          • 2





            @Qwertie: In JS, everything is an object. :) They copied that from Java, who copied it from SmallTalk, who went all the way to the end with it. It’s a nice case of “emergence”, making life easier in general.

            – Evi1M4chine
            Jun 30 '16 at 14:54











          • @Evi1M4chine actually in Java, functions are not objects (and neither are primitives, for that matter)... and objects don't have prototypes, so the comparison seems un-fitting. The fact that JS works differently than other popular OO languages is a major source of confusion (and it doesn't help that browsers don't provide an easy way to visualize the network of objects including functions and prototypes). P.S. I found this link helpful : davidwalsh.name/javascript-objects-deconstruction

            – Qwertie
            Jul 2 '16 at 4:27










          21




          21





          +1 Simplicity and clarity! (Though the Object.create(null) seems a nice option - maybe should mention that).

          – user949300
          Sep 3 '14 at 4:15





          +1 Simplicity and clarity! (Though the Object.create(null) seems a nice option - maybe should mention that).

          – user949300
          Sep 3 '14 at 4:15













          keep it simple that's the way to go

          – Bruce
          May 26 '16 at 12:12





          keep it simple that's the way to go

          – Bruce
          May 26 '16 at 12:12













          That just leaves the question of "wait, so functions have prototypes too? What's the relationship between those and object prototypes?"

          – Qwertie
          May 31 '16 at 22:46





          That just leaves the question of "wait, so functions have prototypes too? What's the relationship between those and object prototypes?"

          – Qwertie
          May 31 '16 at 22:46




          2




          2





          @Qwertie: In JS, everything is an object. :) They copied that from Java, who copied it from SmallTalk, who went all the way to the end with it. It’s a nice case of “emergence”, making life easier in general.

          – Evi1M4chine
          Jun 30 '16 at 14:54





          @Qwertie: In JS, everything is an object. :) They copied that from Java, who copied it from SmallTalk, who went all the way to the end with it. It’s a nice case of “emergence”, making life easier in general.

          – Evi1M4chine
          Jun 30 '16 at 14:54













          @Evi1M4chine actually in Java, functions are not objects (and neither are primitives, for that matter)... and objects don't have prototypes, so the comparison seems un-fitting. The fact that JS works differently than other popular OO languages is a major source of confusion (and it doesn't help that browsers don't provide an easy way to visualize the network of objects including functions and prototypes). P.S. I found this link helpful : davidwalsh.name/javascript-objects-deconstruction

          – Qwertie
          Jul 2 '16 at 4:27







          @Evi1M4chine actually in Java, functions are not objects (and neither are primitives, for that matter)... and objects don't have prototypes, so the comparison seems un-fitting. The fact that JS works differently than other popular OO languages is a major source of confusion (and it doesn't help that browsers don't provide an easy way to visualize the network of objects including functions and prototypes). P.S. I found this link helpful : davidwalsh.name/javascript-objects-deconstruction

          – Qwertie
          Jul 2 '16 at 4:27













          188














          Here are the steps that happen internally for both calls:

          (Hint: the only difference is in step 3)





          new Test():




          1. create new Object() obj

          2. set obj.__proto__ to Test.prototype

          3. return Test.call(obj) || obj;
            // normally obj is returned but constructors in JS can return a value




          Object.create( Test.prototype )




          1. create new Object() obj

          2. set obj.__proto__ to Test.prototype

          3. return obj;




          So basically Object.create doesn't execute the constructor.






          share|improve this answer


























          • @Ray so using object.create we font have the properties of function mentioned in constructor function?

            – user2156081
            Feb 21 '17 at 12:28











          • @sortednoun as long as the properties are private and not specified on the prototype, yes, they won't be inherited and you won't have them in the new object (and, I would add, you can expect to get eventual prototyped properties from the parent, just when the parent constructor has been execute at least once).

            – Kamafeather
            Jul 25 '17 at 16:52
















          188














          Here are the steps that happen internally for both calls:

          (Hint: the only difference is in step 3)





          new Test():




          1. create new Object() obj

          2. set obj.__proto__ to Test.prototype

          3. return Test.call(obj) || obj;
            // normally obj is returned but constructors in JS can return a value




          Object.create( Test.prototype )




          1. create new Object() obj

          2. set obj.__proto__ to Test.prototype

          3. return obj;




          So basically Object.create doesn't execute the constructor.






          share|improve this answer


























          • @Ray so using object.create we font have the properties of function mentioned in constructor function?

            – user2156081
            Feb 21 '17 at 12:28











          • @sortednoun as long as the properties are private and not specified on the prototype, yes, they won't be inherited and you won't have them in the new object (and, I would add, you can expect to get eventual prototyped properties from the parent, just when the parent constructor has been execute at least once).

            – Kamafeather
            Jul 25 '17 at 16:52














          188












          188








          188







          Here are the steps that happen internally for both calls:

          (Hint: the only difference is in step 3)





          new Test():




          1. create new Object() obj

          2. set obj.__proto__ to Test.prototype

          3. return Test.call(obj) || obj;
            // normally obj is returned but constructors in JS can return a value




          Object.create( Test.prototype )




          1. create new Object() obj

          2. set obj.__proto__ to Test.prototype

          3. return obj;




          So basically Object.create doesn't execute the constructor.






          share|improve this answer















          Here are the steps that happen internally for both calls:

          (Hint: the only difference is in step 3)





          new Test():




          1. create new Object() obj

          2. set obj.__proto__ to Test.prototype

          3. return Test.call(obj) || obj;
            // normally obj is returned but constructors in JS can return a value




          Object.create( Test.prototype )




          1. create new Object() obj

          2. set obj.__proto__ to Test.prototype

          3. return obj;




          So basically Object.create doesn't execute the constructor.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Feb 13 '17 at 12:40

























          answered Jan 29 '13 at 23:23









          Ray HulhaRay Hulha

          6,91543140




          6,91543140













          • @Ray so using object.create we font have the properties of function mentioned in constructor function?

            – user2156081
            Feb 21 '17 at 12:28











          • @sortednoun as long as the properties are private and not specified on the prototype, yes, they won't be inherited and you won't have them in the new object (and, I would add, you can expect to get eventual prototyped properties from the parent, just when the parent constructor has been execute at least once).

            – Kamafeather
            Jul 25 '17 at 16:52



















          • @Ray so using object.create we font have the properties of function mentioned in constructor function?

            – user2156081
            Feb 21 '17 at 12:28











          • @sortednoun as long as the properties are private and not specified on the prototype, yes, they won't be inherited and you won't have them in the new object (and, I would add, you can expect to get eventual prototyped properties from the parent, just when the parent constructor has been execute at least once).

            – Kamafeather
            Jul 25 '17 at 16:52

















          @Ray so using object.create we font have the properties of function mentioned in constructor function?

          – user2156081
          Feb 21 '17 at 12:28





          @Ray so using object.create we font have the properties of function mentioned in constructor function?

          – user2156081
          Feb 21 '17 at 12:28













          @sortednoun as long as the properties are private and not specified on the prototype, yes, they won't be inherited and you won't have them in the new object (and, I would add, you can expect to get eventual prototyped properties from the parent, just when the parent constructor has been execute at least once).

          – Kamafeather
          Jul 25 '17 at 16:52





          @sortednoun as long as the properties are private and not specified on the prototype, yes, they won't be inherited and you won't have them in the new object (and, I would add, you can expect to get eventual prototyped properties from the parent, just when the parent constructor has been execute at least once).

          – Kamafeather
          Jul 25 '17 at 16:52











          59














          Let me try to explain (more on Blog) :




          1. When you write Car constructor var Car = function(){}, this is how things are internally:
            A diagram of prototypal chains when creating javascript objects
            We have one {prototype} hidden link to Function.prototype which is not accessible and one prototype link to Car.prototype which is accessible and has an actual constructor of Car. Both Function.prototype and Car.prototype have hidden links to Object.prototype.


          2. When we want to create two equivalent objects by using the new operator and create method then we have to do it like this: Honda = new Car(); and Maruti = Object.create(Car.prototype).A diagram of prototypal chains for differing object creation methods
            What is happening?



            Honda = new Car(); — When you create an object like this then hidden {prototype} property is pointed to Car.prototype. So here, the {prototype} of the Honda object will always be Car.prototype — we don't have any option to change the {prototype} property of the object. What if I want to change the prototype of our newly created object?
            Maruti = Object.create(Car.prototype) — When you create an object like this you have an extra option to choose your object's {prototype} property. If you want Car.prototype as the {prototype} then pass it as a parameter in the function. If you don't want any {prototype} for your object then you can pass null like this: Maruti = Object.create(null).




          Conclusion — By using the method Object.create you have the freedom to choose your object {prototype} property. In new Car();, you don't have that freedom.



          Preferred way in OO JavaScript :



          Suppose we have two objects a and b.



          var a = new Object();
          var b = new Object();


          Now, suppose a has some methods which b also wants to access. For that, we require object inheritance (a should be the prototype of b only if we want access to those methods). If we check the prototypes of a and b then we will find out that they share the prototype Object.prototype.



          Object.prototype.isPrototypeOf(b); //true
          a.isPrototypeOf(b); //false (the problem comes into the picture here).


          Problem — we want object a as the prototype of b, but here we created object b with the prototype Object.prototype.
          Solution — ECMAScript 5 introduced Object.create(), to achieve such inheritance easily. If we create object b like this:



          var b = Object.create(a);


          then,



          a.isPrototypeOf(b);// true (problem solved, you included object a in the prototype chain of object b.)


          So, if you are doing object oriented scripting then Object.create() is very useful for inheritance.






          share|improve this answer


























          • So, it is somewhat similar to object creation without constructor invocation? We will enjoy all the benefits of the class. The obj instanceof Class will also be true. But we are not invoking the Class function via new.

            – Praveen
            Mar 30 '16 at 8:49











          • @Anshul You said that a.isPrototypeOf(b); will return false which is right, because both Objects are different and pointing to different memory. The correct way to do this with the new operator is here. - jsfiddle.net/167onunp .

            – Sagar Karira
            Nov 10 '16 at 11:29













          • Why wouldn't you just set the prototype property of b to a, instead of doing this?

            – Amnestic
            Dec 3 '16 at 19:09











          • Liked the article on your blog too. Helped me understand the concept much better. Thank you.

            – steady_daddy
            Aug 9 '17 at 9:59











          • The conclusion says it all.

            – kushalvm
            Aug 14 '17 at 11:20
















          59














          Let me try to explain (more on Blog) :




          1. When you write Car constructor var Car = function(){}, this is how things are internally:
            A diagram of prototypal chains when creating javascript objects
            We have one {prototype} hidden link to Function.prototype which is not accessible and one prototype link to Car.prototype which is accessible and has an actual constructor of Car. Both Function.prototype and Car.prototype have hidden links to Object.prototype.


          2. When we want to create two equivalent objects by using the new operator and create method then we have to do it like this: Honda = new Car(); and Maruti = Object.create(Car.prototype).A diagram of prototypal chains for differing object creation methods
            What is happening?



            Honda = new Car(); — When you create an object like this then hidden {prototype} property is pointed to Car.prototype. So here, the {prototype} of the Honda object will always be Car.prototype — we don't have any option to change the {prototype} property of the object. What if I want to change the prototype of our newly created object?
            Maruti = Object.create(Car.prototype) — When you create an object like this you have an extra option to choose your object's {prototype} property. If you want Car.prototype as the {prototype} then pass it as a parameter in the function. If you don't want any {prototype} for your object then you can pass null like this: Maruti = Object.create(null).




          Conclusion — By using the method Object.create you have the freedom to choose your object {prototype} property. In new Car();, you don't have that freedom.



          Preferred way in OO JavaScript :



          Suppose we have two objects a and b.



          var a = new Object();
          var b = new Object();


          Now, suppose a has some methods which b also wants to access. For that, we require object inheritance (a should be the prototype of b only if we want access to those methods). If we check the prototypes of a and b then we will find out that they share the prototype Object.prototype.



          Object.prototype.isPrototypeOf(b); //true
          a.isPrototypeOf(b); //false (the problem comes into the picture here).


          Problem — we want object a as the prototype of b, but here we created object b with the prototype Object.prototype.
          Solution — ECMAScript 5 introduced Object.create(), to achieve such inheritance easily. If we create object b like this:



          var b = Object.create(a);


          then,



          a.isPrototypeOf(b);// true (problem solved, you included object a in the prototype chain of object b.)


          So, if you are doing object oriented scripting then Object.create() is very useful for inheritance.






          share|improve this answer


























          • So, it is somewhat similar to object creation without constructor invocation? We will enjoy all the benefits of the class. The obj instanceof Class will also be true. But we are not invoking the Class function via new.

            – Praveen
            Mar 30 '16 at 8:49











          • @Anshul You said that a.isPrototypeOf(b); will return false which is right, because both Objects are different and pointing to different memory. The correct way to do this with the new operator is here. - jsfiddle.net/167onunp .

            – Sagar Karira
            Nov 10 '16 at 11:29













          • Why wouldn't you just set the prototype property of b to a, instead of doing this?

            – Amnestic
            Dec 3 '16 at 19:09











          • Liked the article on your blog too. Helped me understand the concept much better. Thank you.

            – steady_daddy
            Aug 9 '17 at 9:59











          • The conclusion says it all.

            – kushalvm
            Aug 14 '17 at 11:20














          59












          59








          59







          Let me try to explain (more on Blog) :




          1. When you write Car constructor var Car = function(){}, this is how things are internally:
            A diagram of prototypal chains when creating javascript objects
            We have one {prototype} hidden link to Function.prototype which is not accessible and one prototype link to Car.prototype which is accessible and has an actual constructor of Car. Both Function.prototype and Car.prototype have hidden links to Object.prototype.


          2. When we want to create two equivalent objects by using the new operator and create method then we have to do it like this: Honda = new Car(); and Maruti = Object.create(Car.prototype).A diagram of prototypal chains for differing object creation methods
            What is happening?



            Honda = new Car(); — When you create an object like this then hidden {prototype} property is pointed to Car.prototype. So here, the {prototype} of the Honda object will always be Car.prototype — we don't have any option to change the {prototype} property of the object. What if I want to change the prototype of our newly created object?
            Maruti = Object.create(Car.prototype) — When you create an object like this you have an extra option to choose your object's {prototype} property. If you want Car.prototype as the {prototype} then pass it as a parameter in the function. If you don't want any {prototype} for your object then you can pass null like this: Maruti = Object.create(null).




          Conclusion — By using the method Object.create you have the freedom to choose your object {prototype} property. In new Car();, you don't have that freedom.



          Preferred way in OO JavaScript :



          Suppose we have two objects a and b.



          var a = new Object();
          var b = new Object();


          Now, suppose a has some methods which b also wants to access. For that, we require object inheritance (a should be the prototype of b only if we want access to those methods). If we check the prototypes of a and b then we will find out that they share the prototype Object.prototype.



          Object.prototype.isPrototypeOf(b); //true
          a.isPrototypeOf(b); //false (the problem comes into the picture here).


          Problem — we want object a as the prototype of b, but here we created object b with the prototype Object.prototype.
          Solution — ECMAScript 5 introduced Object.create(), to achieve such inheritance easily. If we create object b like this:



          var b = Object.create(a);


          then,



          a.isPrototypeOf(b);// true (problem solved, you included object a in the prototype chain of object b.)


          So, if you are doing object oriented scripting then Object.create() is very useful for inheritance.






          share|improve this answer















          Let me try to explain (more on Blog) :




          1. When you write Car constructor var Car = function(){}, this is how things are internally:
            A diagram of prototypal chains when creating javascript objects
            We have one {prototype} hidden link to Function.prototype which is not accessible and one prototype link to Car.prototype which is accessible and has an actual constructor of Car. Both Function.prototype and Car.prototype have hidden links to Object.prototype.


          2. When we want to create two equivalent objects by using the new operator and create method then we have to do it like this: Honda = new Car(); and Maruti = Object.create(Car.prototype).A diagram of prototypal chains for differing object creation methods
            What is happening?



            Honda = new Car(); — When you create an object like this then hidden {prototype} property is pointed to Car.prototype. So here, the {prototype} of the Honda object will always be Car.prototype — we don't have any option to change the {prototype} property of the object. What if I want to change the prototype of our newly created object?
            Maruti = Object.create(Car.prototype) — When you create an object like this you have an extra option to choose your object's {prototype} property. If you want Car.prototype as the {prototype} then pass it as a parameter in the function. If you don't want any {prototype} for your object then you can pass null like this: Maruti = Object.create(null).




          Conclusion — By using the method Object.create you have the freedom to choose your object {prototype} property. In new Car();, you don't have that freedom.



          Preferred way in OO JavaScript :



          Suppose we have two objects a and b.



          var a = new Object();
          var b = new Object();


          Now, suppose a has some methods which b also wants to access. For that, we require object inheritance (a should be the prototype of b only if we want access to those methods). If we check the prototypes of a and b then we will find out that they share the prototype Object.prototype.



          Object.prototype.isPrototypeOf(b); //true
          a.isPrototypeOf(b); //false (the problem comes into the picture here).


          Problem — we want object a as the prototype of b, but here we created object b with the prototype Object.prototype.
          Solution — ECMAScript 5 introduced Object.create(), to achieve such inheritance easily. If we create object b like this:



          var b = Object.create(a);


          then,



          a.isPrototypeOf(b);// true (problem solved, you included object a in the prototype chain of object b.)


          So, if you are doing object oriented scripting then Object.create() is very useful for inheritance.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 18 '17 at 3:39









          BrassApparatus

          155418




          155418










          answered Sep 3 '14 at 3:45









          AnshulAnshul

          6,19464263




          6,19464263













          • So, it is somewhat similar to object creation without constructor invocation? We will enjoy all the benefits of the class. The obj instanceof Class will also be true. But we are not invoking the Class function via new.

            – Praveen
            Mar 30 '16 at 8:49











          • @Anshul You said that a.isPrototypeOf(b); will return false which is right, because both Objects are different and pointing to different memory. The correct way to do this with the new operator is here. - jsfiddle.net/167onunp .

            – Sagar Karira
            Nov 10 '16 at 11:29













          • Why wouldn't you just set the prototype property of b to a, instead of doing this?

            – Amnestic
            Dec 3 '16 at 19:09











          • Liked the article on your blog too. Helped me understand the concept much better. Thank you.

            – steady_daddy
            Aug 9 '17 at 9:59











          • The conclusion says it all.

            – kushalvm
            Aug 14 '17 at 11:20



















          • So, it is somewhat similar to object creation without constructor invocation? We will enjoy all the benefits of the class. The obj instanceof Class will also be true. But we are not invoking the Class function via new.

            – Praveen
            Mar 30 '16 at 8:49











          • @Anshul You said that a.isPrototypeOf(b); will return false which is right, because both Objects are different and pointing to different memory. The correct way to do this with the new operator is here. - jsfiddle.net/167onunp .

            – Sagar Karira
            Nov 10 '16 at 11:29













          • Why wouldn't you just set the prototype property of b to a, instead of doing this?

            – Amnestic
            Dec 3 '16 at 19:09











          • Liked the article on your blog too. Helped me understand the concept much better. Thank you.

            – steady_daddy
            Aug 9 '17 at 9:59











          • The conclusion says it all.

            – kushalvm
            Aug 14 '17 at 11:20

















          So, it is somewhat similar to object creation without constructor invocation? We will enjoy all the benefits of the class. The obj instanceof Class will also be true. But we are not invoking the Class function via new.

          – Praveen
          Mar 30 '16 at 8:49





          So, it is somewhat similar to object creation without constructor invocation? We will enjoy all the benefits of the class. The obj instanceof Class will also be true. But we are not invoking the Class function via new.

          – Praveen
          Mar 30 '16 at 8:49













          @Anshul You said that a.isPrototypeOf(b); will return false which is right, because both Objects are different and pointing to different memory. The correct way to do this with the new operator is here. - jsfiddle.net/167onunp .

          – Sagar Karira
          Nov 10 '16 at 11:29







          @Anshul You said that a.isPrototypeOf(b); will return false which is right, because both Objects are different and pointing to different memory. The correct way to do this with the new operator is here. - jsfiddle.net/167onunp .

          – Sagar Karira
          Nov 10 '16 at 11:29















          Why wouldn't you just set the prototype property of b to a, instead of doing this?

          – Amnestic
          Dec 3 '16 at 19:09





          Why wouldn't you just set the prototype property of b to a, instead of doing this?

          – Amnestic
          Dec 3 '16 at 19:09













          Liked the article on your blog too. Helped me understand the concept much better. Thank you.

          – steady_daddy
          Aug 9 '17 at 9:59





          Liked the article on your blog too. Helped me understand the concept much better. Thank you.

          – steady_daddy
          Aug 9 '17 at 9:59













          The conclusion says it all.

          – kushalvm
          Aug 14 '17 at 11:20





          The conclusion says it all.

          – kushalvm
          Aug 14 '17 at 11:20











          37














          This:



          var foo = new Foo();


          and



          var foo = Object.create(Foo.prototype);


          are quite similar. One important difference is that new Foo actually runs constructor code, whereas Object.create will not execute code such as



          function Foo() {
          alert("This constructor does not run with Object.create");
          }


          Note that if you use the two-parameter version of Object.create() then you can do much more powerful things.






          share|improve this answer



















          • 1





            Great explanation. Might I add, using Object.create in its simplest form like this allows you to omit constructor functions from your code while taking advantage of prototype inheritance.

            – Ricky Boyce
            Nov 19 '15 at 4:38


















          37














          This:



          var foo = new Foo();


          and



          var foo = Object.create(Foo.prototype);


          are quite similar. One important difference is that new Foo actually runs constructor code, whereas Object.create will not execute code such as



          function Foo() {
          alert("This constructor does not run with Object.create");
          }


          Note that if you use the two-parameter version of Object.create() then you can do much more powerful things.






          share|improve this answer



















          • 1





            Great explanation. Might I add, using Object.create in its simplest form like this allows you to omit constructor functions from your code while taking advantage of prototype inheritance.

            – Ricky Boyce
            Nov 19 '15 at 4:38
















          37












          37








          37







          This:



          var foo = new Foo();


          and



          var foo = Object.create(Foo.prototype);


          are quite similar. One important difference is that new Foo actually runs constructor code, whereas Object.create will not execute code such as



          function Foo() {
          alert("This constructor does not run with Object.create");
          }


          Note that if you use the two-parameter version of Object.create() then you can do much more powerful things.






          share|improve this answer













          This:



          var foo = new Foo();


          and



          var foo = Object.create(Foo.prototype);


          are quite similar. One important difference is that new Foo actually runs constructor code, whereas Object.create will not execute code such as



          function Foo() {
          alert("This constructor does not run with Object.create");
          }


          Note that if you use the two-parameter version of Object.create() then you can do much more powerful things.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Apr 21 '14 at 19:27









          LeopdLeopd

          26k26103149




          26k26103149








          • 1





            Great explanation. Might I add, using Object.create in its simplest form like this allows you to omit constructor functions from your code while taking advantage of prototype inheritance.

            – Ricky Boyce
            Nov 19 '15 at 4:38
















          • 1





            Great explanation. Might I add, using Object.create in its simplest form like this allows you to omit constructor functions from your code while taking advantage of prototype inheritance.

            – Ricky Boyce
            Nov 19 '15 at 4:38










          1




          1





          Great explanation. Might I add, using Object.create in its simplest form like this allows you to omit constructor functions from your code while taking advantage of prototype inheritance.

          – Ricky Boyce
          Nov 19 '15 at 4:38







          Great explanation. Might I add, using Object.create in its simplest form like this allows you to omit constructor functions from your code while taking advantage of prototype inheritance.

          – Ricky Boyce
          Nov 19 '15 at 4:38













          21














          The difference is the so-called "pseudoclassical vs. prototypal inheritance". The suggestion is to use only one type in your code, not mixing the two.



          In pseudoclassical inheritance (with "new" operator), imagine that you first define a pseudo-class, and then create objects from that class. For example, define a pseudo-class "Person", and then create "Alice" and "Bob" from "Person".



          In prototypal inheritance (using Object.create), you directly create a specific person "Alice", and then create another person "Bob" using "Alice" as a prototype. There is no "class" here; all are objects.



          Internally, JavaScript uses "prototypal inheritance"; the "pseudoclassical" way is just some sugar.



          See this link for a comparison of the two ways.






          share|improve this answer




























            21














            The difference is the so-called "pseudoclassical vs. prototypal inheritance". The suggestion is to use only one type in your code, not mixing the two.



            In pseudoclassical inheritance (with "new" operator), imagine that you first define a pseudo-class, and then create objects from that class. For example, define a pseudo-class "Person", and then create "Alice" and "Bob" from "Person".



            In prototypal inheritance (using Object.create), you directly create a specific person "Alice", and then create another person "Bob" using "Alice" as a prototype. There is no "class" here; all are objects.



            Internally, JavaScript uses "prototypal inheritance"; the "pseudoclassical" way is just some sugar.



            See this link for a comparison of the two ways.






            share|improve this answer


























              21












              21








              21







              The difference is the so-called "pseudoclassical vs. prototypal inheritance". The suggestion is to use only one type in your code, not mixing the two.



              In pseudoclassical inheritance (with "new" operator), imagine that you first define a pseudo-class, and then create objects from that class. For example, define a pseudo-class "Person", and then create "Alice" and "Bob" from "Person".



              In prototypal inheritance (using Object.create), you directly create a specific person "Alice", and then create another person "Bob" using "Alice" as a prototype. There is no "class" here; all are objects.



              Internally, JavaScript uses "prototypal inheritance"; the "pseudoclassical" way is just some sugar.



              See this link for a comparison of the two ways.






              share|improve this answer













              The difference is the so-called "pseudoclassical vs. prototypal inheritance". The suggestion is to use only one type in your code, not mixing the two.



              In pseudoclassical inheritance (with "new" operator), imagine that you first define a pseudo-class, and then create objects from that class. For example, define a pseudo-class "Person", and then create "Alice" and "Bob" from "Person".



              In prototypal inheritance (using Object.create), you directly create a specific person "Alice", and then create another person "Bob" using "Alice" as a prototype. There is no "class" here; all are objects.



              Internally, JavaScript uses "prototypal inheritance"; the "pseudoclassical" way is just some sugar.



              See this link for a comparison of the two ways.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Jun 22 '13 at 0:28









              user1931858user1931858

              7,3181135




              7,3181135























                  20














                  function Test(){
                  this.prop1 = 'prop1';
                  this.prop2 = 'prop2';
                  this.func1 = function(){
                  return this.prop1 + this.prop2;
                  }
                  };

                  Test.prototype.protoProp1 = 'protoProp1';
                  Test.prototype.protoProp2 = 'protoProp2';
                  var newKeywordTest = new Test();
                  var objectCreateTest = Object.create(Test.prototype);

                  /* Object.create */
                  console.log(objectCreateTest.prop1); // undefined
                  console.log(objectCreateTest.protoProp1); // protoProp1
                  console.log(objectCreateTest.__proto__.protoProp1); // protoProp1

                  /* new */
                  console.log(newKeywordTest.prop1); // prop1
                  console.log(newKeywordTest.__proto__.protoProp1); // protoProp1


                  Summary:



                  1) with new keyword there are two things to note;



                  a) function is used as a constructor



                  b) function.prototype object is passed to the __proto__ property ... or where __proto__ is not supported, it is the second place where the new object looks to find properties



                  2) with Object.create(obj.prototype) you are constructing an object (obj.prototype) and passing it to the intended object ..with the difference that now new object's __proto__ is also pointing to obj.prototype (please ref ans by xj9 for that)






                  share|improve this answer






























                    20














                    function Test(){
                    this.prop1 = 'prop1';
                    this.prop2 = 'prop2';
                    this.func1 = function(){
                    return this.prop1 + this.prop2;
                    }
                    };

                    Test.prototype.protoProp1 = 'protoProp1';
                    Test.prototype.protoProp2 = 'protoProp2';
                    var newKeywordTest = new Test();
                    var objectCreateTest = Object.create(Test.prototype);

                    /* Object.create */
                    console.log(objectCreateTest.prop1); // undefined
                    console.log(objectCreateTest.protoProp1); // protoProp1
                    console.log(objectCreateTest.__proto__.protoProp1); // protoProp1

                    /* new */
                    console.log(newKeywordTest.prop1); // prop1
                    console.log(newKeywordTest.__proto__.protoProp1); // protoProp1


                    Summary:



                    1) with new keyword there are two things to note;



                    a) function is used as a constructor



                    b) function.prototype object is passed to the __proto__ property ... or where __proto__ is not supported, it is the second place where the new object looks to find properties



                    2) with Object.create(obj.prototype) you are constructing an object (obj.prototype) and passing it to the intended object ..with the difference that now new object's __proto__ is also pointing to obj.prototype (please ref ans by xj9 for that)






                    share|improve this answer




























                      20












                      20








                      20







                      function Test(){
                      this.prop1 = 'prop1';
                      this.prop2 = 'prop2';
                      this.func1 = function(){
                      return this.prop1 + this.prop2;
                      }
                      };

                      Test.prototype.protoProp1 = 'protoProp1';
                      Test.prototype.protoProp2 = 'protoProp2';
                      var newKeywordTest = new Test();
                      var objectCreateTest = Object.create(Test.prototype);

                      /* Object.create */
                      console.log(objectCreateTest.prop1); // undefined
                      console.log(objectCreateTest.protoProp1); // protoProp1
                      console.log(objectCreateTest.__proto__.protoProp1); // protoProp1

                      /* new */
                      console.log(newKeywordTest.prop1); // prop1
                      console.log(newKeywordTest.__proto__.protoProp1); // protoProp1


                      Summary:



                      1) with new keyword there are two things to note;



                      a) function is used as a constructor



                      b) function.prototype object is passed to the __proto__ property ... or where __proto__ is not supported, it is the second place where the new object looks to find properties



                      2) with Object.create(obj.prototype) you are constructing an object (obj.prototype) and passing it to the intended object ..with the difference that now new object's __proto__ is also pointing to obj.prototype (please ref ans by xj9 for that)






                      share|improve this answer















                      function Test(){
                      this.prop1 = 'prop1';
                      this.prop2 = 'prop2';
                      this.func1 = function(){
                      return this.prop1 + this.prop2;
                      }
                      };

                      Test.prototype.protoProp1 = 'protoProp1';
                      Test.prototype.protoProp2 = 'protoProp2';
                      var newKeywordTest = new Test();
                      var objectCreateTest = Object.create(Test.prototype);

                      /* Object.create */
                      console.log(objectCreateTest.prop1); // undefined
                      console.log(objectCreateTest.protoProp1); // protoProp1
                      console.log(objectCreateTest.__proto__.protoProp1); // protoProp1

                      /* new */
                      console.log(newKeywordTest.prop1); // prop1
                      console.log(newKeywordTest.__proto__.protoProp1); // protoProp1


                      Summary:



                      1) with new keyword there are two things to note;



                      a) function is used as a constructor



                      b) function.prototype object is passed to the __proto__ property ... or where __proto__ is not supported, it is the second place where the new object looks to find properties



                      2) with Object.create(obj.prototype) you are constructing an object (obj.prototype) and passing it to the intended object ..with the difference that now new object's __proto__ is also pointing to obj.prototype (please ref ans by xj9 for that)







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jul 22 '15 at 11:34









                      Pedro del Sol

                      2,34483442




                      2,34483442










                      answered Dec 21 '13 at 0:18









                      user3124360user3124360

                      28849




                      28849























                          10














                          Internally Object.create does this:



                          Object.create = function (o) {
                          function F() {}
                          F.prototype = o;
                          return new F();
                          };


                          The syntax just takes away the illusion that JavaScript uses Classical Inheritance.






                          share|improve this answer



















                          • 24





                            The ECMAScript 5 Object.create method, does a lot more than that, you can define properties by property descriptors and you can create an object that doesn't inherit from anything (Object.create(null);), this type of shims should be avoided because you can't really emulate that behavior on ES3. More info

                            – CMS
                            Nov 12 '10 at 16:24













                          • Hmm, did not know.

                            – xj9
                            Nov 12 '10 at 19:25











                          • Agree with @CMS but in general, it is simple polyfill for Object.create.

                            – Vladimir Kovpak
                            Jul 27 '17 at 21:02
















                          10














                          Internally Object.create does this:



                          Object.create = function (o) {
                          function F() {}
                          F.prototype = o;
                          return new F();
                          };


                          The syntax just takes away the illusion that JavaScript uses Classical Inheritance.






                          share|improve this answer



















                          • 24





                            The ECMAScript 5 Object.create method, does a lot more than that, you can define properties by property descriptors and you can create an object that doesn't inherit from anything (Object.create(null);), this type of shims should be avoided because you can't really emulate that behavior on ES3. More info

                            – CMS
                            Nov 12 '10 at 16:24













                          • Hmm, did not know.

                            – xj9
                            Nov 12 '10 at 19:25











                          • Agree with @CMS but in general, it is simple polyfill for Object.create.

                            – Vladimir Kovpak
                            Jul 27 '17 at 21:02














                          10












                          10








                          10







                          Internally Object.create does this:



                          Object.create = function (o) {
                          function F() {}
                          F.prototype = o;
                          return new F();
                          };


                          The syntax just takes away the illusion that JavaScript uses Classical Inheritance.






                          share|improve this answer













                          Internally Object.create does this:



                          Object.create = function (o) {
                          function F() {}
                          F.prototype = o;
                          return new F();
                          };


                          The syntax just takes away the illusion that JavaScript uses Classical Inheritance.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 12 '10 at 16:19









                          xj9xj9

                          2,32421721




                          2,32421721








                          • 24





                            The ECMAScript 5 Object.create method, does a lot more than that, you can define properties by property descriptors and you can create an object that doesn't inherit from anything (Object.create(null);), this type of shims should be avoided because you can't really emulate that behavior on ES3. More info

                            – CMS
                            Nov 12 '10 at 16:24













                          • Hmm, did not know.

                            – xj9
                            Nov 12 '10 at 19:25











                          • Agree with @CMS but in general, it is simple polyfill for Object.create.

                            – Vladimir Kovpak
                            Jul 27 '17 at 21:02














                          • 24





                            The ECMAScript 5 Object.create method, does a lot more than that, you can define properties by property descriptors and you can create an object that doesn't inherit from anything (Object.create(null);), this type of shims should be avoided because you can't really emulate that behavior on ES3. More info

                            – CMS
                            Nov 12 '10 at 16:24













                          • Hmm, did not know.

                            – xj9
                            Nov 12 '10 at 19:25











                          • Agree with @CMS but in general, it is simple polyfill for Object.create.

                            – Vladimir Kovpak
                            Jul 27 '17 at 21:02








                          24




                          24





                          The ECMAScript 5 Object.create method, does a lot more than that, you can define properties by property descriptors and you can create an object that doesn't inherit from anything (Object.create(null);), this type of shims should be avoided because you can't really emulate that behavior on ES3. More info

                          – CMS
                          Nov 12 '10 at 16:24







                          The ECMAScript 5 Object.create method, does a lot more than that, you can define properties by property descriptors and you can create an object that doesn't inherit from anything (Object.create(null);), this type of shims should be avoided because you can't really emulate that behavior on ES3. More info

                          – CMS
                          Nov 12 '10 at 16:24















                          Hmm, did not know.

                          – xj9
                          Nov 12 '10 at 19:25





                          Hmm, did not know.

                          – xj9
                          Nov 12 '10 at 19:25













                          Agree with @CMS but in general, it is simple polyfill for Object.create.

                          – Vladimir Kovpak
                          Jul 27 '17 at 21:02





                          Agree with @CMS but in general, it is simple polyfill for Object.create.

                          – Vladimir Kovpak
                          Jul 27 '17 at 21:02











                          9














                          Accordingly to this answer and to this video new keyword does next things:




                          1. Creates new object.


                          2. Links new object to constructor function (prototype).


                          3. Makes this variable point to the new object.


                          4. Executes constructor function using the new object and implicit perform return this;


                          5. Assigns constructor function name to new object's property constructor.



                          Object.create performs only 1st and 2nd steps!!!






                          share|improve this answer




























                            9














                            Accordingly to this answer and to this video new keyword does next things:




                            1. Creates new object.


                            2. Links new object to constructor function (prototype).


                            3. Makes this variable point to the new object.


                            4. Executes constructor function using the new object and implicit perform return this;


                            5. Assigns constructor function name to new object's property constructor.



                            Object.create performs only 1st and 2nd steps!!!






                            share|improve this answer


























                              9












                              9








                              9







                              Accordingly to this answer and to this video new keyword does next things:




                              1. Creates new object.


                              2. Links new object to constructor function (prototype).


                              3. Makes this variable point to the new object.


                              4. Executes constructor function using the new object and implicit perform return this;


                              5. Assigns constructor function name to new object's property constructor.



                              Object.create performs only 1st and 2nd steps!!!






                              share|improve this answer













                              Accordingly to this answer and to this video new keyword does next things:




                              1. Creates new object.


                              2. Links new object to constructor function (prototype).


                              3. Makes this variable point to the new object.


                              4. Executes constructor function using the new object and implicit perform return this;


                              5. Assigns constructor function name to new object's property constructor.



                              Object.create performs only 1st and 2nd steps!!!







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jul 27 '17 at 19:55









                              Vladimir KovpakVladimir Kovpak

                              11k43749




                              11k43749























                                  6














                                  Object creation variants.





                                  Variant 1 : 'new Object()' -> Object constructor without arguments.



                                  var p1 = new Object(); // 'new Object()' create and return empty object -> {}

                                  var p2 = new Object(); // 'new Object()' create and return empty object -> {}

                                  console.log(p1); // empty object -> {}

                                  console.log(p2); // empty object -> {}

                                  // p1 and p2 are pointers to different objects
                                  console.log(p1 === p2); // false

                                  console.log(p1.prototype); // undefined

                                  // empty object which is in fact Object.prototype
                                  console.log(p1.__proto__); // {}

                                  // empty object to which p1.__proto__ points
                                  console.log(Object.prototype); // {}

                                  console.log(p1.__proto__ === Object.prototype); // true

                                  // null, which is in fact Object.prototype.__proto__
                                  console.log(p1.__proto__.__proto__); // null

                                  console.log(Object.prototype.__proto__); // null


                                  enter image description here





                                  Variant 2 : 'new Object(person)' -> Object constructor with argument.



                                  const person = {
                                  name: 'no name',
                                  lastName: 'no lastName',
                                  age: -1
                                  }

                                  // 'new Object(person)' return 'person', which is pointer to the object ->
                                  // -> { name: 'no name', lastName: 'no lastName', age: -1 }
                                  var p1 = new Object(person);

                                  // 'new Object(person)' return 'person', which is pointer to the object ->
                                  // -> { name: 'no name', lastName: 'no lastName', age: -1 }
                                  var p2 = new Object(person);

                                  // person, p1 and p2 are pointers to the same object
                                  console.log(p1 === p2); // true
                                  console.log(p1 === person); // true
                                  console.log(p2 === person); // true

                                  p1.name = 'John'; // change 'name' by 'p1'
                                  p2.lastName = 'Doe'; // change 'lastName' by 'p2'
                                  person.age = 25; // change 'age' by 'person'

                                  // when print 'p1', 'p2' and 'person', it's the same result,
                                  // because the object they points is the same
                                  console.log(p1); // { name: 'John', lastName: 'Doe', age: 25 }
                                  console.log(p2); // { name: 'John', lastName: 'Doe', age: 25 }
                                  console.log(person); // { name: 'John', lastName: 'Doe', age: 25 }


                                  enter image description here





                                  Variant 3.1 : 'Object.create(person)'. Use Object.create with simple object 'person'. 'Object.create(person)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'person'.



                                  const person = {
                                  name: 'no name',
                                  lastName: 'no lastName',
                                  age: -1,
                                  getInfo: function getName() {
                                  return `${this.name} ${this.lastName}, ${this.age}!`;
                                  }
                                  }

                                  var p1 = Object.create(person);

                                  var p2 = Object.create(person);

                                  // 'p1.__proto__' and 'p2.__proto__' points to
                                  // the same object -> 'person'
                                  // { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
                                  console.log(p1.__proto__);
                                  console.log(p2.__proto__);
                                  console.log(p1.__proto__ === p2.__proto__); // true

                                  console.log(person.__proto__); // {}(which is the Object.prototype)

                                  // 'person', 'p1' and 'p2' are different
                                  console.log(p1 === person); // false
                                  console.log(p1 === p2); // false
                                  console.log(p2 === person); // false

                                  // { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
                                  console.log(person);

                                  console.log(p1); // empty object - {}

                                  console.log(p2); // empty object - {}

                                  // add properties to object 'p1'
                                  // (properties with the same names like in object 'person')
                                  p1.name = 'John';
                                  p1.lastName = 'Doe';
                                  p1.age = 25;

                                  // add properties to object 'p2'
                                  // (properties with the same names like in object 'person')
                                  p2.name = 'Tom';
                                  p2.lastName = 'Harrison';
                                  p2.age = 38;

                                  // { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
                                  console.log(person);

                                  // { name: 'John', lastName: 'Doe', age: 25 }
                                  console.log(p1);

                                  // { name: 'Tom', lastName: 'Harrison', age: 38 }
                                  console.log(p2);

                                  // use by '__proto__'(link from 'p1' to 'person'),
                                  // person's function 'getInfo'
                                  console.log(p1.getInfo()); // John Doe, 25!

                                  // use by '__proto__'(link from 'p2' to 'person'),
                                  // person's function 'getInfo'
                                  console.log(p2.getInfo()); // Tom Harrison, 38!


                                  enter image description here





                                  Variant 3.2 : 'Object.create(Object.prototype)'. Use Object.create with built-in object -> 'Object.prototype'. 'Object.create(Object.prototype)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'Object.prototype'.



                                  // 'Object.create(Object.prototype)' :
                                  // 1. create and return empty object -> {}.
                                  // 2. add to 'p1' property '__proto__', which is link to 'Object.prototype'
                                  var p1 = Object.create(Object.prototype);

                                  // 'Object.create(Object.prototype)' :
                                  // 1. create and return empty object -> {}.
                                  // 2. add to 'p2' property '__proto__', which is link to 'Object.prototype'
                                  var p2 = Object.create(Object.prototype);

                                  console.log(p1); // {}

                                  console.log(p2); // {}

                                  console.log(p1 === p2); // false

                                  console.log(p1.prototype); // undefined

                                  console.log(p2.prototype); // undefined

                                  console.log(p1.__proto__ === Object.prototype); // true

                                  console.log(p2.__proto__ === Object.prototype); // true


                                  enter image description here





                                  Variant 4 : 'new SomeFunction()'



                                  // 'this' in constructor-function 'Person'
                                  // represents a new instace,
                                  // that will be created by 'new Person(...)'
                                  // and returned implicitly
                                  function Person(name, lastName, age) {

                                  this.name = name;
                                  this.lastName = lastName;
                                  this.age = age;

                                  //-----------------------------------------------------------------
                                  // !--- only for demonstration ---
                                  // if add function 'getInfo' into
                                  // constructor-function 'Person',
                                  // then all instances will have a copy of the function 'getInfo'!
                                  //
                                  // this.getInfo: function getInfo() {
                                  // return this.name + " " + this.lastName + ", " + this.age + "!";
                                  // }
                                  //-----------------------------------------------------------------
                                  }

                                  // 'Person.prototype' is an empty object
                                  // (before add function 'getInfo')
                                  console.log(Person.prototype); // Person {}

                                  // With 'getInfo' added to 'Person.prototype',
                                  // instances by their properties '__proto__',
                                  // will have access to the function 'getInfo'.
                                  // With this approach, instances not need
                                  // a copy of the function 'getInfo' for every instance.
                                  Person.prototype.getInfo = function getInfo() {
                                  return this.name + " " + this.lastName + ", " + this.age + "!";
                                  }

                                  // after function 'getInfo' is added to 'Person.prototype'
                                  console.log(Person.prototype); // Person { getInfo: [Function: getInfo] }

                                  // create instance 'p1'
                                  var p1 = new Person('John', 'Doe', 25);

                                  // create instance 'p2'
                                  var p2 = new Person('Tom', 'Harrison', 38);

                                  // Person { name: 'John', lastName: 'Doe', age: 25 }
                                  console.log(p1);

                                  // Person { name: 'Tom', lastName: 'Harrison', age: 38 }
                                  console.log(p2);

                                  // 'p1.__proto__' points to 'Person.prototype'
                                  console.log(p1.__proto__); // Person { getInfo: [Function: getInfo] }

                                  // 'p2.__proto__' points to 'Person.prototype'
                                  console.log(p2.__proto__); // Person { getInfo: [Function: getInfo] }

                                  console.log(p1.__proto__ === p2.__proto__); // true

                                  // 'p1' and 'p2' points to different objects(instaces of 'Person')
                                  console.log(p1 === p2); // false

                                  // 'p1' by its property '__proto__' reaches 'Person.prototype.getInfo'
                                  // and use 'getInfo' with 'p1'-instance's data
                                  console.log(p1.getInfo()); // John Doe, 25!

                                  // 'p2' by its property '__proto__' reaches 'Person.prototype.getInfo'
                                  // and use 'getInfo' with 'p2'-instance's data
                                  console.log(p2.getInfo()); // Tom Harrison, 38!


                                  enter image description here






                                  share|improve this answer






























                                    6














                                    Object creation variants.





                                    Variant 1 : 'new Object()' -> Object constructor without arguments.



                                    var p1 = new Object(); // 'new Object()' create and return empty object -> {}

                                    var p2 = new Object(); // 'new Object()' create and return empty object -> {}

                                    console.log(p1); // empty object -> {}

                                    console.log(p2); // empty object -> {}

                                    // p1 and p2 are pointers to different objects
                                    console.log(p1 === p2); // false

                                    console.log(p1.prototype); // undefined

                                    // empty object which is in fact Object.prototype
                                    console.log(p1.__proto__); // {}

                                    // empty object to which p1.__proto__ points
                                    console.log(Object.prototype); // {}

                                    console.log(p1.__proto__ === Object.prototype); // true

                                    // null, which is in fact Object.prototype.__proto__
                                    console.log(p1.__proto__.__proto__); // null

                                    console.log(Object.prototype.__proto__); // null


                                    enter image description here





                                    Variant 2 : 'new Object(person)' -> Object constructor with argument.



                                    const person = {
                                    name: 'no name',
                                    lastName: 'no lastName',
                                    age: -1
                                    }

                                    // 'new Object(person)' return 'person', which is pointer to the object ->
                                    // -> { name: 'no name', lastName: 'no lastName', age: -1 }
                                    var p1 = new Object(person);

                                    // 'new Object(person)' return 'person', which is pointer to the object ->
                                    // -> { name: 'no name', lastName: 'no lastName', age: -1 }
                                    var p2 = new Object(person);

                                    // person, p1 and p2 are pointers to the same object
                                    console.log(p1 === p2); // true
                                    console.log(p1 === person); // true
                                    console.log(p2 === person); // true

                                    p1.name = 'John'; // change 'name' by 'p1'
                                    p2.lastName = 'Doe'; // change 'lastName' by 'p2'
                                    person.age = 25; // change 'age' by 'person'

                                    // when print 'p1', 'p2' and 'person', it's the same result,
                                    // because the object they points is the same
                                    console.log(p1); // { name: 'John', lastName: 'Doe', age: 25 }
                                    console.log(p2); // { name: 'John', lastName: 'Doe', age: 25 }
                                    console.log(person); // { name: 'John', lastName: 'Doe', age: 25 }


                                    enter image description here





                                    Variant 3.1 : 'Object.create(person)'. Use Object.create with simple object 'person'. 'Object.create(person)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'person'.



                                    const person = {
                                    name: 'no name',
                                    lastName: 'no lastName',
                                    age: -1,
                                    getInfo: function getName() {
                                    return `${this.name} ${this.lastName}, ${this.age}!`;
                                    }
                                    }

                                    var p1 = Object.create(person);

                                    var p2 = Object.create(person);

                                    // 'p1.__proto__' and 'p2.__proto__' points to
                                    // the same object -> 'person'
                                    // { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
                                    console.log(p1.__proto__);
                                    console.log(p2.__proto__);
                                    console.log(p1.__proto__ === p2.__proto__); // true

                                    console.log(person.__proto__); // {}(which is the Object.prototype)

                                    // 'person', 'p1' and 'p2' are different
                                    console.log(p1 === person); // false
                                    console.log(p1 === p2); // false
                                    console.log(p2 === person); // false

                                    // { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
                                    console.log(person);

                                    console.log(p1); // empty object - {}

                                    console.log(p2); // empty object - {}

                                    // add properties to object 'p1'
                                    // (properties with the same names like in object 'person')
                                    p1.name = 'John';
                                    p1.lastName = 'Doe';
                                    p1.age = 25;

                                    // add properties to object 'p2'
                                    // (properties with the same names like in object 'person')
                                    p2.name = 'Tom';
                                    p2.lastName = 'Harrison';
                                    p2.age = 38;

                                    // { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
                                    console.log(person);

                                    // { name: 'John', lastName: 'Doe', age: 25 }
                                    console.log(p1);

                                    // { name: 'Tom', lastName: 'Harrison', age: 38 }
                                    console.log(p2);

                                    // use by '__proto__'(link from 'p1' to 'person'),
                                    // person's function 'getInfo'
                                    console.log(p1.getInfo()); // John Doe, 25!

                                    // use by '__proto__'(link from 'p2' to 'person'),
                                    // person's function 'getInfo'
                                    console.log(p2.getInfo()); // Tom Harrison, 38!


                                    enter image description here





                                    Variant 3.2 : 'Object.create(Object.prototype)'. Use Object.create with built-in object -> 'Object.prototype'. 'Object.create(Object.prototype)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'Object.prototype'.



                                    // 'Object.create(Object.prototype)' :
                                    // 1. create and return empty object -> {}.
                                    // 2. add to 'p1' property '__proto__', which is link to 'Object.prototype'
                                    var p1 = Object.create(Object.prototype);

                                    // 'Object.create(Object.prototype)' :
                                    // 1. create and return empty object -> {}.
                                    // 2. add to 'p2' property '__proto__', which is link to 'Object.prototype'
                                    var p2 = Object.create(Object.prototype);

                                    console.log(p1); // {}

                                    console.log(p2); // {}

                                    console.log(p1 === p2); // false

                                    console.log(p1.prototype); // undefined

                                    console.log(p2.prototype); // undefined

                                    console.log(p1.__proto__ === Object.prototype); // true

                                    console.log(p2.__proto__ === Object.prototype); // true


                                    enter image description here





                                    Variant 4 : 'new SomeFunction()'



                                    // 'this' in constructor-function 'Person'
                                    // represents a new instace,
                                    // that will be created by 'new Person(...)'
                                    // and returned implicitly
                                    function Person(name, lastName, age) {

                                    this.name = name;
                                    this.lastName = lastName;
                                    this.age = age;

                                    //-----------------------------------------------------------------
                                    // !--- only for demonstration ---
                                    // if add function 'getInfo' into
                                    // constructor-function 'Person',
                                    // then all instances will have a copy of the function 'getInfo'!
                                    //
                                    // this.getInfo: function getInfo() {
                                    // return this.name + " " + this.lastName + ", " + this.age + "!";
                                    // }
                                    //-----------------------------------------------------------------
                                    }

                                    // 'Person.prototype' is an empty object
                                    // (before add function 'getInfo')
                                    console.log(Person.prototype); // Person {}

                                    // With 'getInfo' added to 'Person.prototype',
                                    // instances by their properties '__proto__',
                                    // will have access to the function 'getInfo'.
                                    // With this approach, instances not need
                                    // a copy of the function 'getInfo' for every instance.
                                    Person.prototype.getInfo = function getInfo() {
                                    return this.name + " " + this.lastName + ", " + this.age + "!";
                                    }

                                    // after function 'getInfo' is added to 'Person.prototype'
                                    console.log(Person.prototype); // Person { getInfo: [Function: getInfo] }

                                    // create instance 'p1'
                                    var p1 = new Person('John', 'Doe', 25);

                                    // create instance 'p2'
                                    var p2 = new Person('Tom', 'Harrison', 38);

                                    // Person { name: 'John', lastName: 'Doe', age: 25 }
                                    console.log(p1);

                                    // Person { name: 'Tom', lastName: 'Harrison', age: 38 }
                                    console.log(p2);

                                    // 'p1.__proto__' points to 'Person.prototype'
                                    console.log(p1.__proto__); // Person { getInfo: [Function: getInfo] }

                                    // 'p2.__proto__' points to 'Person.prototype'
                                    console.log(p2.__proto__); // Person { getInfo: [Function: getInfo] }

                                    console.log(p1.__proto__ === p2.__proto__); // true

                                    // 'p1' and 'p2' points to different objects(instaces of 'Person')
                                    console.log(p1 === p2); // false

                                    // 'p1' by its property '__proto__' reaches 'Person.prototype.getInfo'
                                    // and use 'getInfo' with 'p1'-instance's data
                                    console.log(p1.getInfo()); // John Doe, 25!

                                    // 'p2' by its property '__proto__' reaches 'Person.prototype.getInfo'
                                    // and use 'getInfo' with 'p2'-instance's data
                                    console.log(p2.getInfo()); // Tom Harrison, 38!


                                    enter image description here






                                    share|improve this answer




























                                      6












                                      6








                                      6







                                      Object creation variants.





                                      Variant 1 : 'new Object()' -> Object constructor without arguments.



                                      var p1 = new Object(); // 'new Object()' create and return empty object -> {}

                                      var p2 = new Object(); // 'new Object()' create and return empty object -> {}

                                      console.log(p1); // empty object -> {}

                                      console.log(p2); // empty object -> {}

                                      // p1 and p2 are pointers to different objects
                                      console.log(p1 === p2); // false

                                      console.log(p1.prototype); // undefined

                                      // empty object which is in fact Object.prototype
                                      console.log(p1.__proto__); // {}

                                      // empty object to which p1.__proto__ points
                                      console.log(Object.prototype); // {}

                                      console.log(p1.__proto__ === Object.prototype); // true

                                      // null, which is in fact Object.prototype.__proto__
                                      console.log(p1.__proto__.__proto__); // null

                                      console.log(Object.prototype.__proto__); // null


                                      enter image description here





                                      Variant 2 : 'new Object(person)' -> Object constructor with argument.



                                      const person = {
                                      name: 'no name',
                                      lastName: 'no lastName',
                                      age: -1
                                      }

                                      // 'new Object(person)' return 'person', which is pointer to the object ->
                                      // -> { name: 'no name', lastName: 'no lastName', age: -1 }
                                      var p1 = new Object(person);

                                      // 'new Object(person)' return 'person', which is pointer to the object ->
                                      // -> { name: 'no name', lastName: 'no lastName', age: -1 }
                                      var p2 = new Object(person);

                                      // person, p1 and p2 are pointers to the same object
                                      console.log(p1 === p2); // true
                                      console.log(p1 === person); // true
                                      console.log(p2 === person); // true

                                      p1.name = 'John'; // change 'name' by 'p1'
                                      p2.lastName = 'Doe'; // change 'lastName' by 'p2'
                                      person.age = 25; // change 'age' by 'person'

                                      // when print 'p1', 'p2' and 'person', it's the same result,
                                      // because the object they points is the same
                                      console.log(p1); // { name: 'John', lastName: 'Doe', age: 25 }
                                      console.log(p2); // { name: 'John', lastName: 'Doe', age: 25 }
                                      console.log(person); // { name: 'John', lastName: 'Doe', age: 25 }


                                      enter image description here





                                      Variant 3.1 : 'Object.create(person)'. Use Object.create with simple object 'person'. 'Object.create(person)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'person'.



                                      const person = {
                                      name: 'no name',
                                      lastName: 'no lastName',
                                      age: -1,
                                      getInfo: function getName() {
                                      return `${this.name} ${this.lastName}, ${this.age}!`;
                                      }
                                      }

                                      var p1 = Object.create(person);

                                      var p2 = Object.create(person);

                                      // 'p1.__proto__' and 'p2.__proto__' points to
                                      // the same object -> 'person'
                                      // { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
                                      console.log(p1.__proto__);
                                      console.log(p2.__proto__);
                                      console.log(p1.__proto__ === p2.__proto__); // true

                                      console.log(person.__proto__); // {}(which is the Object.prototype)

                                      // 'person', 'p1' and 'p2' are different
                                      console.log(p1 === person); // false
                                      console.log(p1 === p2); // false
                                      console.log(p2 === person); // false

                                      // { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
                                      console.log(person);

                                      console.log(p1); // empty object - {}

                                      console.log(p2); // empty object - {}

                                      // add properties to object 'p1'
                                      // (properties with the same names like in object 'person')
                                      p1.name = 'John';
                                      p1.lastName = 'Doe';
                                      p1.age = 25;

                                      // add properties to object 'p2'
                                      // (properties with the same names like in object 'person')
                                      p2.name = 'Tom';
                                      p2.lastName = 'Harrison';
                                      p2.age = 38;

                                      // { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
                                      console.log(person);

                                      // { name: 'John', lastName: 'Doe', age: 25 }
                                      console.log(p1);

                                      // { name: 'Tom', lastName: 'Harrison', age: 38 }
                                      console.log(p2);

                                      // use by '__proto__'(link from 'p1' to 'person'),
                                      // person's function 'getInfo'
                                      console.log(p1.getInfo()); // John Doe, 25!

                                      // use by '__proto__'(link from 'p2' to 'person'),
                                      // person's function 'getInfo'
                                      console.log(p2.getInfo()); // Tom Harrison, 38!


                                      enter image description here





                                      Variant 3.2 : 'Object.create(Object.prototype)'. Use Object.create with built-in object -> 'Object.prototype'. 'Object.create(Object.prototype)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'Object.prototype'.



                                      // 'Object.create(Object.prototype)' :
                                      // 1. create and return empty object -> {}.
                                      // 2. add to 'p1' property '__proto__', which is link to 'Object.prototype'
                                      var p1 = Object.create(Object.prototype);

                                      // 'Object.create(Object.prototype)' :
                                      // 1. create and return empty object -> {}.
                                      // 2. add to 'p2' property '__proto__', which is link to 'Object.prototype'
                                      var p2 = Object.create(Object.prototype);

                                      console.log(p1); // {}

                                      console.log(p2); // {}

                                      console.log(p1 === p2); // false

                                      console.log(p1.prototype); // undefined

                                      console.log(p2.prototype); // undefined

                                      console.log(p1.__proto__ === Object.prototype); // true

                                      console.log(p2.__proto__ === Object.prototype); // true


                                      enter image description here





                                      Variant 4 : 'new SomeFunction()'



                                      // 'this' in constructor-function 'Person'
                                      // represents a new instace,
                                      // that will be created by 'new Person(...)'
                                      // and returned implicitly
                                      function Person(name, lastName, age) {

                                      this.name = name;
                                      this.lastName = lastName;
                                      this.age = age;

                                      //-----------------------------------------------------------------
                                      // !--- only for demonstration ---
                                      // if add function 'getInfo' into
                                      // constructor-function 'Person',
                                      // then all instances will have a copy of the function 'getInfo'!
                                      //
                                      // this.getInfo: function getInfo() {
                                      // return this.name + " " + this.lastName + ", " + this.age + "!";
                                      // }
                                      //-----------------------------------------------------------------
                                      }

                                      // 'Person.prototype' is an empty object
                                      // (before add function 'getInfo')
                                      console.log(Person.prototype); // Person {}

                                      // With 'getInfo' added to 'Person.prototype',
                                      // instances by their properties '__proto__',
                                      // will have access to the function 'getInfo'.
                                      // With this approach, instances not need
                                      // a copy of the function 'getInfo' for every instance.
                                      Person.prototype.getInfo = function getInfo() {
                                      return this.name + " " + this.lastName + ", " + this.age + "!";
                                      }

                                      // after function 'getInfo' is added to 'Person.prototype'
                                      console.log(Person.prototype); // Person { getInfo: [Function: getInfo] }

                                      // create instance 'p1'
                                      var p1 = new Person('John', 'Doe', 25);

                                      // create instance 'p2'
                                      var p2 = new Person('Tom', 'Harrison', 38);

                                      // Person { name: 'John', lastName: 'Doe', age: 25 }
                                      console.log(p1);

                                      // Person { name: 'Tom', lastName: 'Harrison', age: 38 }
                                      console.log(p2);

                                      // 'p1.__proto__' points to 'Person.prototype'
                                      console.log(p1.__proto__); // Person { getInfo: [Function: getInfo] }

                                      // 'p2.__proto__' points to 'Person.prototype'
                                      console.log(p2.__proto__); // Person { getInfo: [Function: getInfo] }

                                      console.log(p1.__proto__ === p2.__proto__); // true

                                      // 'p1' and 'p2' points to different objects(instaces of 'Person')
                                      console.log(p1 === p2); // false

                                      // 'p1' by its property '__proto__' reaches 'Person.prototype.getInfo'
                                      // and use 'getInfo' with 'p1'-instance's data
                                      console.log(p1.getInfo()); // John Doe, 25!

                                      // 'p2' by its property '__proto__' reaches 'Person.prototype.getInfo'
                                      // and use 'getInfo' with 'p2'-instance's data
                                      console.log(p2.getInfo()); // Tom Harrison, 38!


                                      enter image description here






                                      share|improve this answer















                                      Object creation variants.





                                      Variant 1 : 'new Object()' -> Object constructor without arguments.



                                      var p1 = new Object(); // 'new Object()' create and return empty object -> {}

                                      var p2 = new Object(); // 'new Object()' create and return empty object -> {}

                                      console.log(p1); // empty object -> {}

                                      console.log(p2); // empty object -> {}

                                      // p1 and p2 are pointers to different objects
                                      console.log(p1 === p2); // false

                                      console.log(p1.prototype); // undefined

                                      // empty object which is in fact Object.prototype
                                      console.log(p1.__proto__); // {}

                                      // empty object to which p1.__proto__ points
                                      console.log(Object.prototype); // {}

                                      console.log(p1.__proto__ === Object.prototype); // true

                                      // null, which is in fact Object.prototype.__proto__
                                      console.log(p1.__proto__.__proto__); // null

                                      console.log(Object.prototype.__proto__); // null


                                      enter image description here





                                      Variant 2 : 'new Object(person)' -> Object constructor with argument.



                                      const person = {
                                      name: 'no name',
                                      lastName: 'no lastName',
                                      age: -1
                                      }

                                      // 'new Object(person)' return 'person', which is pointer to the object ->
                                      // -> { name: 'no name', lastName: 'no lastName', age: -1 }
                                      var p1 = new Object(person);

                                      // 'new Object(person)' return 'person', which is pointer to the object ->
                                      // -> { name: 'no name', lastName: 'no lastName', age: -1 }
                                      var p2 = new Object(person);

                                      // person, p1 and p2 are pointers to the same object
                                      console.log(p1 === p2); // true
                                      console.log(p1 === person); // true
                                      console.log(p2 === person); // true

                                      p1.name = 'John'; // change 'name' by 'p1'
                                      p2.lastName = 'Doe'; // change 'lastName' by 'p2'
                                      person.age = 25; // change 'age' by 'person'

                                      // when print 'p1', 'p2' and 'person', it's the same result,
                                      // because the object they points is the same
                                      console.log(p1); // { name: 'John', lastName: 'Doe', age: 25 }
                                      console.log(p2); // { name: 'John', lastName: 'Doe', age: 25 }
                                      console.log(person); // { name: 'John', lastName: 'Doe', age: 25 }


                                      enter image description here





                                      Variant 3.1 : 'Object.create(person)'. Use Object.create with simple object 'person'. 'Object.create(person)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'person'.



                                      const person = {
                                      name: 'no name',
                                      lastName: 'no lastName',
                                      age: -1,
                                      getInfo: function getName() {
                                      return `${this.name} ${this.lastName}, ${this.age}!`;
                                      }
                                      }

                                      var p1 = Object.create(person);

                                      var p2 = Object.create(person);

                                      // 'p1.__proto__' and 'p2.__proto__' points to
                                      // the same object -> 'person'
                                      // { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
                                      console.log(p1.__proto__);
                                      console.log(p2.__proto__);
                                      console.log(p1.__proto__ === p2.__proto__); // true

                                      console.log(person.__proto__); // {}(which is the Object.prototype)

                                      // 'person', 'p1' and 'p2' are different
                                      console.log(p1 === person); // false
                                      console.log(p1 === p2); // false
                                      console.log(p2 === person); // false

                                      // { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
                                      console.log(person);

                                      console.log(p1); // empty object - {}

                                      console.log(p2); // empty object - {}

                                      // add properties to object 'p1'
                                      // (properties with the same names like in object 'person')
                                      p1.name = 'John';
                                      p1.lastName = 'Doe';
                                      p1.age = 25;

                                      // add properties to object 'p2'
                                      // (properties with the same names like in object 'person')
                                      p2.name = 'Tom';
                                      p2.lastName = 'Harrison';
                                      p2.age = 38;

                                      // { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
                                      console.log(person);

                                      // { name: 'John', lastName: 'Doe', age: 25 }
                                      console.log(p1);

                                      // { name: 'Tom', lastName: 'Harrison', age: 38 }
                                      console.log(p2);

                                      // use by '__proto__'(link from 'p1' to 'person'),
                                      // person's function 'getInfo'
                                      console.log(p1.getInfo()); // John Doe, 25!

                                      // use by '__proto__'(link from 'p2' to 'person'),
                                      // person's function 'getInfo'
                                      console.log(p2.getInfo()); // Tom Harrison, 38!


                                      enter image description here





                                      Variant 3.2 : 'Object.create(Object.prototype)'. Use Object.create with built-in object -> 'Object.prototype'. 'Object.create(Object.prototype)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'Object.prototype'.



                                      // 'Object.create(Object.prototype)' :
                                      // 1. create and return empty object -> {}.
                                      // 2. add to 'p1' property '__proto__', which is link to 'Object.prototype'
                                      var p1 = Object.create(Object.prototype);

                                      // 'Object.create(Object.prototype)' :
                                      // 1. create and return empty object -> {}.
                                      // 2. add to 'p2' property '__proto__', which is link to 'Object.prototype'
                                      var p2 = Object.create(Object.prototype);

                                      console.log(p1); // {}

                                      console.log(p2); // {}

                                      console.log(p1 === p2); // false

                                      console.log(p1.prototype); // undefined

                                      console.log(p2.prototype); // undefined

                                      console.log(p1.__proto__ === Object.prototype); // true

                                      console.log(p2.__proto__ === Object.prototype); // true


                                      enter image description here





                                      Variant 4 : 'new SomeFunction()'



                                      // 'this' in constructor-function 'Person'
                                      // represents a new instace,
                                      // that will be created by 'new Person(...)'
                                      // and returned implicitly
                                      function Person(name, lastName, age) {

                                      this.name = name;
                                      this.lastName = lastName;
                                      this.age = age;

                                      //-----------------------------------------------------------------
                                      // !--- only for demonstration ---
                                      // if add function 'getInfo' into
                                      // constructor-function 'Person',
                                      // then all instances will have a copy of the function 'getInfo'!
                                      //
                                      // this.getInfo: function getInfo() {
                                      // return this.name + " " + this.lastName + ", " + this.age + "!";
                                      // }
                                      //-----------------------------------------------------------------
                                      }

                                      // 'Person.prototype' is an empty object
                                      // (before add function 'getInfo')
                                      console.log(Person.prototype); // Person {}

                                      // With 'getInfo' added to 'Person.prototype',
                                      // instances by their properties '__proto__',
                                      // will have access to the function 'getInfo'.
                                      // With this approach, instances not need
                                      // a copy of the function 'getInfo' for every instance.
                                      Person.prototype.getInfo = function getInfo() {
                                      return this.name + " " + this.lastName + ", " + this.age + "!";
                                      }

                                      // after function 'getInfo' is added to 'Person.prototype'
                                      console.log(Person.prototype); // Person { getInfo: [Function: getInfo] }

                                      // create instance 'p1'
                                      var p1 = new Person('John', 'Doe', 25);

                                      // create instance 'p2'
                                      var p2 = new Person('Tom', 'Harrison', 38);

                                      // Person { name: 'John', lastName: 'Doe', age: 25 }
                                      console.log(p1);

                                      // Person { name: 'Tom', lastName: 'Harrison', age: 38 }
                                      console.log(p2);

                                      // 'p1.__proto__' points to 'Person.prototype'
                                      console.log(p1.__proto__); // Person { getInfo: [Function: getInfo] }

                                      // 'p2.__proto__' points to 'Person.prototype'
                                      console.log(p2.__proto__); // Person { getInfo: [Function: getInfo] }

                                      console.log(p1.__proto__ === p2.__proto__); // true

                                      // 'p1' and 'p2' points to different objects(instaces of 'Person')
                                      console.log(p1 === p2); // false

                                      // 'p1' by its property '__proto__' reaches 'Person.prototype.getInfo'
                                      // and use 'getInfo' with 'p1'-instance's data
                                      console.log(p1.getInfo()); // John Doe, 25!

                                      // 'p2' by its property '__proto__' reaches 'Person.prototype.getInfo'
                                      // and use 'getInfo' with 'p2'-instance's data
                                      console.log(p2.getInfo()); // Tom Harrison, 38!


                                      enter image description here







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Mar 24 '18 at 13:56

























                                      answered Mar 22 '18 at 17:29









                                      TedTed

                                      18913




                                      18913






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4166616%2funderstanding-the-difference-between-object-create-and-new-somefunction%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          The Sandy Post

                                          Danny Elfman

                                          Pages that link to "Head v. Amoskeag Manufacturing Co."