JS: Prototypes
In addition to their own properties, almost all JavaScript objects also have a prototype. A prototype is another object that is used as a fallback source of properties. The ancestral prototype, the entity behind all objects, is Object.prototype
.
Many objects don’t directly have Object.prototype
as their prototype, but instead have another object, which provides its own default properties. Such a prototype object will itself have a prototype, often Object.prototype
, so that it still indirectly provides methods like toString
. Functions derive from Function.prototype
and arrays derive from Array.prototype
.
var empty = {}
console.log(empty.toString) // -> function toString()...{}
console.log(empty.toString()) // -> [object Object]
Object.getPrototypeOf
function returns the prototype of an object. You can use Object.create
to create an object with a specific prototype.
var protoRabbit = {
speak: () => {
console.log("I am Proto Rabbit!")
}
}
var killerRabbit = Object.create(protoRabbit)
killerRabbit.speak() // -> I am a Proto Rabbit!
To create an object without any prototype (not even Object.prototype
) you can use the Object.create
method. Since our protoLessObject
has no prototype all of the properties will be its own properties, so we won’t need the Object.hasOwnProperty
kludge.
var protoLessObject = Object.create(null)