javascript - 我如何确定一个对象在 Javascript 中是 "custom"?

标签 javascript object

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

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

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

if(typeof myCustomObj == "object") {

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

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

最佳答案

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

关于javascript - 我如何确定一个对象在 Javascript 中是 "custom"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10357481/

相关文章:

Java:重构后加载保存在硬盘上的对象 => "class not found"异常:/

javascript - 在 AngularJS 应用程序中使用 Lo-Dash 从 REST 返回总和

javascript - 如何在 jQuery Mobile 中更改选项卡时捕获事件

javascript - 适用于 Evernote 和 OneDrive 的文件选择器 API

javascript - 使用 jQuery Validate 验证数组

javascript - 如何构造具有动态值和多级数组的 json

javascript - 从vue js中的多选框中检索选定的值

javascript - 动态滑动框宽度 css 问题

javascript - 删除对象中的虚假值

javascript - 获取对象的路径并将其转换为 JavaScript 中的字符串