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.
var personFullName = personObjLit.greetFullName();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.
Object.createcreates a new object with its prototype set to the object you pass it. Consider this code:You only want to use
Object.createwhen 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.