admin管理员组文章数量:1355051
This is probably a stupid question, so please stick with me.
Why do I see so many examples testing whether an object is a Function by paring its toString() to "[object Function]"?
For example:
function isFunction(obj) {
return Object.prototype.toString.call(obj) == "[object Function]";
}
Can't we use instanceof Function
or obj.constructor === Function
? Are those not cross-browser patible?
This seems inefficient, but is it? Why?
This is probably a stupid question, so please stick with me.
Why do I see so many examples testing whether an object is a Function by paring its toString() to "[object Function]"?
For example:
function isFunction(obj) {
return Object.prototype.toString.call(obj) == "[object Function]";
}
Can't we use instanceof Function
or obj.constructor === Function
? Are those not cross-browser patible?
This seems inefficient, but is it? Why?
Share Improve this question asked Dec 3, 2010 at 15:58 Eric WendelinEric Wendelin 44.4k9 gold badges72 silver badges94 bronze badges 1- possible duplicate of jQuery's isFunction and InternetExplorer – meder omuraliev Commented Dec 3, 2010 at 16:04
2 Answers
Reset to default 7Short answer is because typeof /foo/
is a function in Webkit browsers. CMS has the long drawn explanation @ jQuery's isFunction and InternetExplorer
And instanceOf
isn't reliable because as Zuriy points out:
The problems arise when it es 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:
Great article @ http://perfectionkills./instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ by Zuriy on the subject.
Example taken from the article:
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
They are not testing its toString method, they are calling Object's prototype's toString method on obj
to cast it to a string. A function casts as '[object Function]' to a string.
instanceof
is not reliable and neither is the constructor way. The constructor requires a check to see if obj
is null or not before attempting to access its constructor property - I'm also guessing it's a tad slower than the toString
method.
本文标签: Use of toString() instead of constructor in JavaScriptStack Overflow
版权声明:本文标题:Use of toString() instead of constructor in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743935138a2564525.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论