I known this has been asked hundreds of times, however, I can\'t seem to grasp the concept of prototype
Here\'s my sample script
var config
The prototype
property only exists on functions, and person
is not a function. It's an object
.
Here's what's happening:
var man = Object.create(null); // man (object) -> null
man.sex = "male";
var person = Object.create(man); // person (object) -> man (object) -> null
person.greet = function () { ... };
var p = Object.getPrototypeOf(person); // man (object) -> null
alert(p.sex); // p is the same object as man
person.prototype.age = 13; // person doesn't have a prototype
var child = function () {}; // child (function) -> Function.prototype
// -> Object.prototype -> null
child.prototype.color = "red"; // child has a prototype
var ch = Object.getPrototypeOf(child); // Function.prototype
alert(ch.color); // ch is not the same as color.prototype
// ch is Function.prototype
For more information I suggest you read this answer: https://stackoverflow.com/a/8096017/783743
Edit: To explain what's happening in as few words as possible:
Everything in JavaScript is an object except primitive values (booleans, numbers and strings), and null
and undefined
.
All objects have a property called [[proto]]
which is not accessible to the programmer. However most engines make this property accessible as __proto__
.
When you create an object like var o = { a: false, b: "something", ... }
then o.__proto__
is Object.prototype
.
When you create an object like var o = Object.create(something)
then o.__proto__
is something
.
When you create an object like var o = new f(a, b, ...)
then o.__proto__
is f.prototype
.
When JavaScript can't find a property on o
it searches for the property on o.__proto__
and then o.__proto__.__proto__
etc until it either finds the property or the proto chain ends in null
(in which case the property is undefined
).
Finally, Object.getPrototypeOf(o)
returns o.__proto__
and not o.prototype
- __proto__
exists on all objects including functions but prototype
only exists on functions.