Suppose we have the following:
function Super() {
// init code
}
function Sub() {
Super.call(this);
// other init code
}
Sub.prototype =
According to this MDN Ref:
isPrototypeOf()
differs from theinstanceof
operator. In the expressionobject instanceof AFunction
, the object prototype chain is checked againstAFunction.prototype
, not againstAFunction
itself.
Just complement @apsillers's answer
object instanceof constructor
var superProto = {}
// subProto.__proto__.__proto__ === superProto
var subProto = Object.create(superProto);
subProto.someProp = 5;
// sub.__proto__.__proto__ === subProto
var sub = Object.create(subProto);
console.log(superProto.isPrototypeOf(sub)); // true
console.log(sub instanceof superProto); // TypeError: Right-hand side of 'instanceof' is not callable
// helper utility to see if `o1` is
// related to (delegates to) `o2`
function isRelatedTo(o1, o2) {
function F(){}
F.prototype = o2;
// ensure the right-hand side of 'instanceof' is callable
return o1 instanceof F;
}
isRelatedTo( b, a );
TypeError: Right-hand side of 'instanceof' is not callable
instanceof
need the right-hand value to be callable, which means it must be a function(MDN call it as the constructor)
and instanceof
tests the presence of constructor.prototype
in object's prototype chain.
but isPrototypeOf()
don't have such limit. While instanceof
checks superProto.prototype
, isPrototypeOf()
checks superProto
directly.
Imagine you don't use constructors in your code, but instead use Object.create to generate objects with a particular prototype. Your program might be architected to use no constructors at all:
var superProto = {
// some super properties
}
var subProto = Object.create(superProto);
subProto.someProp = 5;
var sub = Object.create(subProto);
console.log(superProto.isPrototypeOf(sub)); // true
console.log(sub instanceof superProto); // TypeError
Here, you don't have a constructor function to use with instanceof
. You can only use subProto.isPrototypeOf(sub)
.
It makes little difference when you use constructor functions. instanceof
is a little cleaner, perhaps. But when you don't...:
var human = {mortal: true}
var socrates = Object.create(human);
human.isPrototypeOf(socrates); //=> true
socrates instanceof human; //=> ERROR!
So isPrototypeOf
is more general.
var neuesArray = Object.create(Array);
Array.isPrototypeOf(neuesArray); // true
neuesArray instanceof Array // false
neuesArray instanceof Object // true
Array.isArray(neuesArray); // false
Array.prototype.isPrototypeOf(neuesArray); // false
Object.prototype.isPrototypeOf(neuesArray); // true
Do you understand my friend :) - is simple