[英]what's the best way to check if one object is a prototype of another?
I believe the best way would be something like:我相信最好的方法是:
var a = {a:1, b:2}
var b = Object.create(a);
b.a = 1
var c = Object.create(b);
c.c = 3;
var d = Object.create(c);
d.protoTree(); //returns: [c, b, a]
c.protoTree(); //returns: [b, a];
b.protoTree(); //returns: [a];
But is this possible?但这可能吗? What's the best way assuming you only know the D object?假设您只知道 D object,那么最好的方法是什么?
You can use isPrototypeOf() for this use case您可以将isPrototypeOf()用于此用例
If wouldn't be good to have that as a member method, but it's easy to implement as a standalone (recursive) function:如果将其作为成员方法并不好,但作为独立(递归)function 很容易实现:
function protoTree(obj){
if(obj === null) return []
return [obj, ...protoTree(Object.getPrototypeOf(obj))]
}
It works like this (note that it also returns Object.prototype
, that a
inherits from.它是这样工作的(请注意,它还返回Object.prototype
, a
继承自。
var a = {a:1, b:2}
var b = Object.create(a);
b.a = 1
var c = Object.create(b);
c.c = 3;
var d = Object.create(c);
//Note that `protoTree` returns the prototype objects themselves, not the variable names they are stored in
protoTree(d); //returns: [c, b, a, Object.prototype]
protoTree(c); //returns: [b, a, Object.prototype]
protoTree(b); //returns: [a, Object.prototype]
protoTree(a); //returns: [Object.prototype]
Using Object.prototype.isPrototypeOf()
is the way to do this使用Object.prototype.isPrototypeOf()
是这样做的方法
function Person() {} function Child() {} Child.prototype = Object.create(Person.prototype); const child = new Child(); console.log(Person.prototype.isPrototypeOf(child)); console.log(Child.prototype.isPrototypeOf(child));
More about Object.prototype.isPrototypeOf()
here更多关于Object.prototype.isPrototypeOf()
在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.