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

Ell*_*lle 2 javascript object

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

if(!typeof myCustomObj == "string" && !typeof myCustomObj  == "number" && !typeof myCustomObj == "boolean") {
Run Code Online (Sandbox Code Playgroud)

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

if(typeof myCustomObj == "object") {
Run Code Online (Sandbox Code Playgroud)

这只适用于原始值,因为这typeof new String("hello world") == "object")是真的.

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

Joe*_*Joe 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);
}
Run Code Online (Sandbox Code Playgroud)

  • @Rocket是的,很明显它会来自上面的代码.我会理解,如果名称"nodeType"是非常奇特的(或更具体,可能像"W3CDomNodeType"),但"nodeType"是一个人可以在不知不觉中轻易使用的东西. (2认同)