这可能是一个愚蠢的问题,所以请坚持我的看法。
为什么我看到那么多示例通过将对象的 toString() 与“[object Function]”进行比较来测试对象是否为 Function?
例如:
function isFunction(obj) {
return Object.prototype.toString.call(obj) == "[object Function]";
}
我们不能使用 instanceof Function
或 obj.constructor === Function
吗?那些不是跨浏览器兼容的吗?
这似乎效率低下,但真的如此吗?为什么?
最佳答案
简短的回答是因为 typeof/foo/
是 Webkit 浏览器中的一个函数。 CMS 有很长的解释@ jQuery's isFunction and InternetExplorer
instanceOf
并不可靠,因为正如 Zuriy 指出的那样:
The problems arise when it comes to scripting in multi-frame DOM environments. In a nutshell, Array objects created within one iframe do not share [[Prototype]]’s with arrays created within another iframe. Their constructors are different objects and so both instanceof and constructor checks fail:
很棒的文章@ http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ Zuriy 关于这个主题。
文章中的示例:
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1,2,3); // [1,2,3]
// Boom!
arr instanceof Array; // false
// Boom!
arr.constructor === Array; // false
关于javascript - 在 JavaScript 中使用 toString() 而不是构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4347298/