【问题标题】:How can I determine that an object is "custom" in Javascript?如何确定对象在 Javascript 中是“自定义”的?
【发布时间】:2012-05-08 14:32:41
【问题描述】:

为了澄清我的标题,我需要一种方法来确定对象不是字符串、数字、布尔值或任何其他预定义的 JavaScript 对象。想到的一种方法是:

if(!typeof myCustomObj == "string" && !typeof myCustomObj  == "number" && !typeof myCustomObj == "boolean") {

我可以检查myCustomObj 是否是一个对象,如下所示:

if(typeof myCustomObj == "object") {

这仅适用于原始值,因为 typeof new String("hello world") == "object") 为真。

确定一个对象是否不是预定义的 JavaScript 对象的可靠方法是什么?

【问题讨论】:

标签: javascript object


【解决方案1】:

您可以在对象原型上使用“toString”函数:

var typ = Object.prototype.toString.call( someTestObject );

这为内置类型提供了“[object String]”或“[object Date]”之类的答案。不幸的是,您无法区分作为普通 Object 实例创建的事物和使用构造函数创建的事物,但从某种意义上说,这些事物并没有太大的不同。

【讨论】:

  • 不幸的是,我需要检测具有自定义属性的普通 Object 实例与内置类型不同,所以我不知道这是否适合我。
  • jQuery 方法的答案非常彻底。
  • Object.prototype.toString.call($()) 返回[object Object],但$.isPlainObject($()) 返回false。仅供参考:-P +1,它应该在大多数情况下都有效,除非您需要非常具体。
【解决方案2】:

这是 jQuery 在jQuery.isPlainObject() 中的操作方式

function (obj) {
    // Must be an Object.
    // Because of IE, we also have to check the presence of the constructor property.
    // Make sure that DOM nodes and window objects don't pass through, as well
    if (!obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj)) {
        return false;
    }

    try {
        // Not own constructor property must be Object
        if (obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
            return false;
        }
    } catch(e) {
        // IE8,9 Will throw exceptions on certain host objects #9897
        return false;
    }

    // Own properties are enumerated firstly, so to speed up,
    // if last one is own, then all properties are own.
    var key;
    for (key in obj) {}

    return key === undefined || hasOwn.call(obj, key);
}

【讨论】:

  • 我认为,仅存在一个名为“nodeType”的属性就会使该函数返回 false,这很弱。 (这是关于 jQuery 的评论,而不是关于您的答案 :-)
  • 这也会调用其他 jQuery 函数,尤其是 jQuery.type。您还可以挖掘该功能的任何更改吗?谢谢。
  • @ElliotBonneville:查看jQuery source viewer。它将链接到其他 jQuery 函数:-P
  • @ElliotBonneville:我实际上是几个小时前在谷歌上发现的:-P
  • @Rocket 是的,很明显它会从上面的代码中。如果“nodeType”这个名字真的很奇特(或者更具体一点,比如“W3CDomNodeType”),我会有点理解,但是“nodeType”是一个很容易在不知不觉中使用的东西。
猜你喜欢
  • 2010-12-08
  • 2010-11-13
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
  • 1970-01-01
  • 1970-01-01
  • 2023-04-11
相关资源
最近更新 更多