为了阐明我的标题,我需要一种方法来确定对象不是字符串、数字、 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/