【问题标题】:What is the difference between Javascript's native `instanceof` operator and MooTools' `instanceOf` function?Javascript 的原生 `instanceof` 运算符和 MooTools 的 `instanceOf` 函数有什么区别?
【发布时间】:2012-09-21 20:10:30
【问题描述】:

MooTools 有自己的instanceOf(instance, Type) 函数。
我只能假设它与 Javascript 的原生 instanceof 运算符有一些不同,但我似乎无法弄清楚是什么。

谁能解释instanceOf()函数的区别或用途?

【问题讨论】:

  • 一个是函数,另一个是运算符。 :)
  • mootools 源代码的相关位位于here
  • @user6607 你忘了说一个是大写的O,另一个是小写的o。
  • @RichardTowers 旁注:我不知道您可以链接到特定的行号!酷!

标签: javascript inheritance mootools


【解决方案1】:

instanceOf 是对 typeOf 的补充,它们是 MooTools 的内部函数,在类型遍历方面比它们的原生函数做得更好。

typeOf 在这方面更有用:

typeof []; // object
typeOf([]); // array
typeof new Date(); // object
typeOf(new Date()); // date

instanceOf 主要用于 Class,尽管它也适用于 Types 构造函数。

例如。

var foo = new Class(),
    bar = new Class({
        Extends: foo
    });

var foobar = new bar();

instanceOf(foobar, bar); // true
// but also due to Extends prototype chain and the constructor:
instanceOf(foobar, foo); // true

// as well as standard behaviour like
instanceOf([], Array); // true
instanceOf(4, Number); // true vs 4 instanceof Number == false

查看来源: https://github.com/mootools/mootools-core/blob/master/Source/Core/Core.js#L47-58

您可能会注意到 mootools 中的许多类型的构造函数装饰对象以简化鸭子类型,因此 typeOf 和 instanceOf 可以产生实际有意义的结果。

另请阅读mootools Type function

【讨论】:

  • 感谢您的回答。我绝对理解typeOftypeof 之间的区别;后者只给出 5 个结果,而前者给出 20 个结果,这是一个相当大的差异。但是您是说instanceOf 的唯一目的是将本机类型与数字和字符串进行比较?
  • 另外,查看instanceOf 源代码,我看到了两件事:1. 手动遍历继承链; 2. 一些ltIE8 代码。我会假设本机instanceof 与#1 的工作方式相同,所以在我看来instanceOf 的唯一目的是ltIE8
  • 这是对$constructor 的检查,它通过类原型装饰所有对象,允许它查找类实例是否是特定构造函数的子对象。其他的东西是奖金,imo。就像我说的,它主要用于类操作。
  • 那么foobar instanceof foo 会是假的吗?我一直认为 MooTools 继承是原生 Javascript 继承的扩展,因此 instanceof 应该在 MooTools 类中正常运行。我错过了什么? 编辑:我刚刚测试了jsfiddle.net/RbTUb,而foobar instanceof foo确实是true
  • var foo = new Class(); console.log(foo instanceof Class); console.log(instanceOf(foo, Class)); - 不是本机 instanceof Class 但它是。 instanceOf 与 mootools 一起工作 在操作员失败的边缘情况下键入,但这是为数不多的真实情况之一。 Class 是通过 Type 构造函数的 Type,因此它被视为 Native...我想不出许多在 Type for Class 参数检查本身之外需要 instanceOf 的用例...
【解决方案2】:

至少:

> "" instanceof String
false
> instanceOf("", String)
true

【讨论】:

  • instanceOf(); 有什么不同?
  • +1 很高兴知道! instanceOf() 比较原生类型,而 instanceof 只比较“盒装”类型。我假设5 instanceof Number 也是如此。
猜你喜欢
  • 1970-01-01
  • 2011-01-28
  • 2011-01-27
  • 2010-10-04
  • 1970-01-01
  • 2013-08-06
  • 2019-04-05
  • 1970-01-01
  • 2013-08-12
相关资源
最近更新 更多