Possible Duplicate:
How does JavaScript .prototype work?
Coming from Java background, I’m trying to understand javascript.
Please let me know if these are right.
- Like in java, there is a supreme Object, from which all other objects inherit.
- The prototype property is like a pointer that points to the parent object (classes in java)
- For “Object” object, the prototype is null.
- prototype property’s values are strings denoting the objects nomenclature and aren’t pointers like in C. The pointer concept is implemented using the hidden attribute,[[PROTOTYPE]] that is not accessible in script.
I’m using node.js instead of browser to learn JS.
I tried,
var human = Object.create(null); // same as var human;
console.log(Object.getPrototypeOf(human)); //null
var man = Object.create(human);
console.log(Object.getPrototypeOf(man));
//{}
//expected 'human'
var person = Object.create(Object.prototype); // same as var person = {}
console.log(Object.getPrototypeOf(person));
//{}
//expected 'object'
Object.create(null)which doesn’t inherit from anything.Object.prototype.toStringexists, so does{}.toString– it is inherited..prototype(or the value returned byObject.getPrototypeOf) is an object which you can extend with properties, so that those properties are inherited by instances.Your examples:
No, it creates an empty object that doesn’t inherit from anything.
var human;setshumantoundefined– which is not an object but a primitive value (not everything is an object in JavaScript).Object.getPrototypeOf(man)returns the objecthuman. This is an empty object; node shows it as{}. It is not a string. In fact, objects can be assigned to multiple variables. An object does not have a variable bound to it, so by design it is not possible at all to get a string. To check equality, you could doObject.getPrototypeOf(man) === humanwhich yieldstrue.This is indeed the same as
{}– an empty object that inherits directly fromObject. As said above, the prototype isObject.prototypeand not a string. It looks empty but that’s becauseObject.prototype‘s functions are available by default and hidden.