JavaScript instanceof
operator uses a prototype chain to return the type of object.
JavaScript instanceof运算符使用原型链来返回对象的类型。
Let say, If i have below hierarchy.
让我们说,如果我有低于等级。
Rabit->Animal->Object->Null
Now if i wanted to know any instance is actually a rabit or animal or Object, I can not do this.
现在,如果我想知道任何实例实际上是一个rabit或动物或对象,我不能这样做。
if (rabbitObj instance of Animal) // true
if (rabbitObj instance of Rabit) // true
if (rabbitObj instance of Object) // true
How can get rabbitObj is actually a Rabbit.
怎么能得到rabbitObj实际上是一只兔子。
How i can get actual type of instance, instead of following prototypical chain.
我如何获得实际类型的实例,而不是遵循原型链。
1 个解决方案
#1
0
You are trying to use JavaScript's delegation behavior as class based languages inheritance but they are different things. In JavaScript you must think in terms of objects and their prototypes, and understand how the delegation can work for you to achieve what you are looking for instead of the inheritance.
您正在尝试将JavaScript的委派行为用作基于类的语言继承,但它们是不同的东西。在JavaScript中,您必须根据对象及其原型进行思考,并了解委派如何为您实现您正在寻找的内容而不是继承。
Read more about the prototype and delegation systems in the You Don't Know JS: this & Object Prototypes book, specifically the Prototypes chapter.
阅读“你不了解JS:本和对象原型”一书中的原型和委托系统的更多内容,特别是Prototypes章节。
#1
0
You are trying to use JavaScript's delegation behavior as class based languages inheritance but they are different things. In JavaScript you must think in terms of objects and their prototypes, and understand how the delegation can work for you to achieve what you are looking for instead of the inheritance.
您正在尝试将JavaScript的委派行为用作基于类的语言继承,但它们是不同的东西。在JavaScript中,您必须根据对象及其原型进行思考,并了解委派如何为您实现您正在寻找的内容而不是继承。
Read more about the prototype and delegation systems in the You Don't Know JS: this & Object Prototypes book, specifically the Prototypes chapter.
阅读“你不了解JS:本和对象原型”一书中的原型和委托系统的更多内容,特别是Prototypes章节。