-4

Suppose this is my object

// Object Literal
var personObjLit = {
    firstname : "John",
    lastname: "Doe",
    greetFullName : function() {
        return "personObjLit says: Hello " + this.firstname +
        ", " + this.lastname;
    }
}

I want to call greetFullName method, I can call it using two methods.

  1. var personFullName = personObjLit.greetFullName();
  2. var personObjLitObject = Object.create(personObjLit);

I want to know what is the difference between these two. I mean it just the different approaches or it affects memory or something else.

Piyush Jain
  • 1,895
  • 3
  • 19
  • 40
  • 3
    Your "2nd way to call greetFullName" doesn't even call greetFullName – Farzher Jul 03 '16 at 07:24
  • *"or it affects memory"* - Well obviously the second way involves having two objects and the first only one, so what do you think? But you wouldn't do one or the other because of memory concerns, you'd do one or the other depending on what the code is supposed to actually do. – nnnnnn Jul 03 '16 at 07:26
  • 1
    The second way creates a new object with `personObjLit` as its prototype, which is unlikely to be what you want to do. –  Jul 03 '16 at 07:26

1 Answers1

0

Object.create creates a new object with its prototype set to the object you pass it. Consider this code:

var a = {};
var b = Object.create(a);

a.propA = 'valueA'; // add a property to a
b.propB = 'valueB'; // add a property to b

a.propA; // "valueA"
b.propB; // "valueB"
b.propA; // "valueA" - inherited from a, which is b's prototype
a.propB; // undefined - only exists on b

You only want to use Object.create when you are interested in creating a new object with a certain prototype. If you have no reason to do this, the the object literal syntax is the way to go.

See https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain for more information about the prototype chain.

Mike Chamberlain
  • 39,692
  • 27
  • 110
  • 158