我想要:
document.createElement('div') //=> true
{tagName: 'foobar something'} //=> false
Run Code Online (Sandbox Code Playgroud)
在我自己的脚本中,我曾经只是使用它,因为我从来不需要tagName作为属性:
if (!object.tagName) throw ...;
Run Code Online (Sandbox Code Playgroud)
因此,对于第二个对象,我想出了以下作为快速解决方案 - 主要是有效的.;)
问题是,它取决于执行只读属性的浏览器,而不是所有人都这样做.
function isDOM(obj) {
var tag = obj.tagName;
try {
obj.tagName = ''; // Read-only for DOM, should throw exception
obj.tagName = tag; // Restore for normal objects
return false;
} catch (e) {
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
有一个很好的替代品吗?
考虑以下:
var o1 = {}
var O = function () {
return this
}
var o2 = new O()
var o3 = function() {}
var o4 = [o1, o1]
var output = [
[_.isObject(o1), _.isObject(o2), _.isObject(o3), _.isObject(o4)],
[_.isPlainObject(o1), _.isPlainObject(o2), _.isPlainObject(o3), _.isPlainObject(o4)],
[typeof o1 === 'object', typeof o2 === 'object', typeof o3 === 'object', typeof o4 === 'object'],
[o1 instanceof Array, o2 instanceof Array, o3 instanceof Array, o4 instanceof Array]
]
/* outputs:
[
[true,true,true,true],
[true,false,false,false],
[true,true,false,true],
[false,false,false,true]
]
*/
Run Code Online (Sandbox Code Playgroud)
很明显,我们可以看到 …
是否有已知的方法或库已经有一个帮助器来评估对象是否可以在JavaScript中序列化?
我尝试了以下但它没有涵盖原型属性,因此它提供误报:
_.isEqual(obj, JSON.parse(JSON.stringify(obj))
Run Code Online (Sandbox Code Playgroud)
还有另一个lodash功能可能让我更接近事实_.isPlainObject.但是,_.isPlainObject(new MyClass())返回false时_.isPlainObject({x: new MyClass()})返回true,因此需要递归应用.
在我自己冒险之前,有没有人知道一种已经可靠的方法来检查是否JSON.parse(JSON.stringify(obj))真的会导致同一个对象obj?