javascript - 在 JavaScript 中使用 toString() 而不是构造函数

标签 javascript

这可能是一个愚蠢的问题,所以请坚持我的看法。

为什么我看到那么多示例通过将对象的 toString() 与“[object Function]”进行比较来测试对象是否为 Function?

例如:

function isFunction(obj) {
    return Object.prototype.toString.call(obj) == "[object Function]";
}

我们不能使用 instanceof Functionobj.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/

相关文章:

javascript - jQuery DataTable 返回带有数据的 PHP 脚本

javascript - 如何显示 window.onbeforeunload 警报的 Bootstrap 模式?

javascript - 如何修复我的代码以显示正确的数组索引

javascript - jQuery 延迟 : cancel progress

javascript - RemoveClass 和 AddClass 不起作用

javascript - 页面刷新后所选选项卡不处于事件状态

javascript - Python 相当于选择第一个非空参数

javascript - javascript 中需要阻塞 sleep

javascript - Jquery 选中和取消选中带有链接的复选框

javascript - 使用 Javascript 动态实现 Spring Security