为什么我们需要isPrototypeOf? [英] Why do we need the isPrototypeOf at all?
问题描述
此页说明:
注意:isPrototypeOf与
instanceof运算符不同。在表达式
object instanceof AFunction中,
对象原型链被检查
对抗AFunction.prototype,而不是
对抗AFunction本身
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
好的,我真的没有得到他们想告诉我们的东西。是不是对象instanceof AFunction
与`AFunction.prototype.isPrototypeOf(object)完全相同?或者我错了?
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?
为什么我们需要 isPrototypeOf
?
如果我需要做 p.isPrototypeOf(o)
我不能只做 o instanceof p.constructor
?
If i ever need to do p.isPrototypeOf(o)
couldn't I just do o instanceof p.constructor
?
另外,是 p.isPrototypeOf(o)
功能相当于 p === Object.getPrototypeOf(o)
?
推荐答案
对象构造函数是时髦的东西。来自此答案:
Object constructors are funky things. From this answer:
正如Pointy指出的那样,在他的
答案中
构造函数属性是
引用创建
对象原型的函数,而不是对象
本身。
The "constructor" property is a reference to the function that created the object's prototype, not the object itself.
通常处理这个的方法是
在将
分配给 prototype <之后,扩充对象的原型
构造函数
属性/ code>。
The usual way to deal with this is to
augment the object's prototype
constructor
property after assigning
to the prototype
.
对象的构造函数不是只读的,这就是为什么可以这样做的原因。在创建 p
之后,我可以为 p.constructor
分配任何值,这将完全破坏
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
而不是
p.isPrototypeOf(o)
进一步阅读
-
构造函数
@ MDC - Javascript构造函数属性的意义是什么?
- JS中的OO编程
- 构造商认为有点混乱
constructor
@ MDC- What it the significance of the Javascript constructor property?
- OO Programming in JS
- Constructors considered mildly confusing
Further reading
编辑 re:OP编辑
Edit re: OP edit
另外,
p.isPrototypeOf(o)
功能相当于p === Object.getPrototypeOf(o)
?
除了事实之外,它们比你原来的问题更相似在JavaScript 1.8.1之前没有引入 Object.getPrototypeOf
?请参阅 John Resig - Object.getPrototypeOf
。也许更相关,这两个功能在规范中有所不同的! (警告,PDF链接)
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)
这篇关于为什么我们需要isPrototypeOf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!