Given the following constructor,
Dog = function(name, age, ...){
Animal.call(this, name, age, ...);
// And some other stuff that dogs do
}
I use the following line of code to copy my methods and properties across from the Animal
class,
Dog.prototype = new Animal();
Could you enlighten me as to how that differs from
Dog.prototype.__proto__ = Animal.prototype;
since they seem to have the same effect.
__proto__
lets you access the internal[[Prototype]]
attribute of an object. It can be used to get or set the prototype of an already existing object.protoype
is a property of a function to set the prototype of objects that will be created by that function.Afaik, only Firefox lets you use
__proto__
. It is not standard and deprecated.Worth reading:
__proto__
is a non-standard extension to JavaScript (common in various interpreters, but non-standard) that gives you direct access to the prototype behind an object. Theprototype
property of function objects is the object that will be assigned as the prototype behind an object created by calling the function vianew
. So when you assign toprototype.__proto__
, you're assigning to the prototype behind the object that will be set as the prototype on new objects created by the function.Since the way the prototype chain works is that properties on a prototype show up as inherited properties on an object (and this continues in a chain), if you assign to
Dog.prototype.__proto__
, the objects created byDog
will have access to those properties indirectly through the chain:When you assign directly to
Dog.prototype
, the instances have a more direct reference:(Note that the above is slightly misleading by referring to
Dog.prototype
like that. Instances ofDog
will get a direct reference to the object onDog.prototype
as of whennew Dog
is called; if you assign a completely different object toDog.prototype
later, instances that already exist will have the old prototype and new instances will get the new one. But that's a side-point.)