最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Use of toString() instead of constructor in JavaScript - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 7

Short 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.

发布评论

评论列表(0)

  1. 暂无评论