问题
this page states:
Note: isPrototypeOf differs from instanceof operator. In the expression object instanceof AFunction, the object prototype chain is checked against AFunction.prototype, not against AFunction itself
Ok I don't really get what they are trying to tell us. Isn't object instanceof AFunction
exactly the same as `AFunction.prototype.isPrototypeOf(object)? or am I wrong?
Why do we need the isPrototypeOf
at all?
If i ever need to do p.isPrototypeOf(o)
couldn't I just do o instanceof p.constructor
?
Addtionally, is p.isPrototypeOf(o)
functionally equivalent to p===Object.getPrototypeOf(o)
?
回答1:
Object constructors are funky things. From this answer:
As Pointy has pointed out, in his answer
The "constructor" property is a reference to the function that created the object's prototype, not the object itself.
The usual way to deal with this is to augment the object's prototype
constructor
property after assigning to theprototype
.
An object's constructor is not read-only, which is why this is possible to do at all. I could assign any value to p.constructor
after p
is created, and this would completely break using
o instanceof p.constructor
instead of
p.isPrototypeOf(o)
Further reading
- constructor @ MDC
- What it the significance of the Javascript constructor property?
- OO Programming in JS
- Constructors considered mildly confusing
Edit re: OP edit
Addtionally, is
p.isPrototypeOf(o)
functionally equivalent top===Object.getPrototypeOf(o)
?
Those are more similar than your original question, aside from the fact that Object.getPrototypeOf
wasn't introduced until JavaScript 1.8.1? See John Resig - Object.getPrototypeOf. Perhaps more relevant, the two functions are different in the spec! (warning, PDF link)


回答2:
I think the most important distinction here is that the isPrototypeOf method allows you to check if an object inherits directly from another object. Consider the following:
var t = new Object();
var f = new Object();
var c = Object.create(t);
c instanceof f.constructor; // true
c instanceof t.constructor; // true
f.isPrototypeOf(c); // false
t.isPrototypeOf(c); // true
As you can see the constructor is only the function that instantiated the object. Not the implementation specifier. So if t.y = function(){ return true; }
and f.y = function(){ return false; }
and I needed to check that c
would return the appropriate implementation through it's prototype chain, instanceof
wouldn't help very much.
回答3:
instanceOf --> This object (or the objects it was derived from ) used the named object as a prototype
isPrototypeOf --> This object was used by the named Object (or the Objects it was derived from) as a prototype.
ie.
instanceOf is querying the objects ancestors.
IsPrototypeOf is querying the objects descendants.
来源:https://stackoverflow.com/questions/5972991/why-do-we-need-the-isprototypeof-at-all