如何在Javascript中确定对象是“自定义”?

时间:2012-04-27 20:34:34

标签: javascript object

为了澄清我的标题,我需要一种方法来确定一个对象不是String,Number,Boolean或任何其他预定义的JavaScript对象。想到的一种方法是:

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

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

if(typeof myCustomObj == "object") {

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

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

2 个答案:

答案 0 :(得分:5)

以下是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);
}

答案 1 :(得分:4)

您可以在Object原型上使用“toString”功能:

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

为内置类型提供“[object String]”或“[object Date]”等答案。遗憾的是,你无法区分用普通的Object实例创建的东西和用构造函数创建的东西之间的那种方式,但从某种意义上说,这些东西实际上并没有那么多不同。