I was going through this post of Crockford on Prototypal Inheritance in JavaScript. He mentions creating Object.create function (which is now included in ECMA Script 5) for creating new objects that inherit from other objects without using the new keyword as it is borrowed from classical languages like Java. The code is:
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
newObject = Object.create(oldObject);
I was wondering why we need to make a constructor function for this? Can't we simply create an empty object using literal notation, change its prototype to old object and return that object? Like this:
if (typeof Object.create !== 'function') {
Object.create = function (o) {
F = {};
F.prototype = o;
return F;
};
}
I tested this approach, but it is not working properly:
var oldObject = { name: "Steve", lastname: "Jobs" };
var newObject = Object.create(oldObject);
console.log(newObject.name); // this outputs undefined.
console.log(newObject.prorotype.name); // this works. But shouldn't newObject.name automatically search the prototype in above code when it did not find the property in the local object?
Here is the fiddle. Note that I have changed the function names to create1 and create2 in the fiddle as I did not want to over-ride the built in create function.
Can someone explain why this is not working as expected?