The Big Daddy of all in Javascript is Object.prototype
Once upon a time daddy was created:
var daddy = {
apples : 10
}
Daddy has only one variable, apples with a value of ten.
daddy; in a repl will return {apples: 10}
Daddy actually has more properties than just the one property of apple, you just can't see them, they've been inherited from the Big Daddy of all objects, the Object.prototype. Big Daddy Object.prototype contains methods that all children objects have access to.
So, daddy was created from Big Daddy, and then one say daddy had a son, name son object;
var son = Object.create(daddy);
Booooom, son is born.
son; run in a repl will return {};
This is because it's an empty object. However son.apples; run in a repl will return 10.
When the browser looks for a property named apples in son, and doesn't find one, it looks up the chain, the Big Daddy chain, or the prototype chain, to the next in line, which is daddy. Booom, inside daddy it finds a variable named apples, and so returns 10.
No comments:
Post a Comment