Why do we need the isPrototypeOf at all?

醉酒当歌 提交于 2019-12-02 18:23:07
Matt Ball

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 the prototype.

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


Edit re: OP edit

Addtionally, is p.isPrototypeOf(o) functionally equivalent to p===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)

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!