I have got an object literal (a), which I later use to make another object (b) add some properties, and again make an object with help of (b), ie (c) and add some properties to it.
Finally, I try access c.name which browser goes on for searching first in c, then b, then finally gets it from object a (same for second alert). But, I am a bit confused if this example correctly represents "Prototypal Inheritance"! (As, function constructure with prototype properties is not involved).
var a = {name: "Jenny", age: 27};
var b = Object.create(a);
b.state = "New York";
var c = Object.create(b);
c.flag = "50 star flag";
alert(c.name);
alert(b.age);
Yes, it does, the prototype chain you created is c -> b -> a
.
var a = {};
var b = Object.create(a);
console.log(Object.getPrototypeOf(b) === a); // true
var c = Object.create(b);
console.log(Object.getPrototypeOf(c) === b); // true
If you're confused about missing constructor functions in this example, remember that Object.create
is just a shortcut for
function Object.create(proto) {
function F() {}
F.prototype = proto;
return new F();
}
so the new
and constructor are still executed under the hood. For the rationale behind Object.create
see this classic article.