Javascript in Object Literal approach difference between calling a method direct and using Object.create?

53 views Asked by At

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.

1

There are 1 answers

0
Mike Chamberlain On

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.