The instanceOf operator came to mind immediately. After all, don't you do the same thing in C#, compare if an object "is" something? Luckily for me, I checked the Internet and reached the faithful StackOverflow with an answer. The interesting bit was explaining why instanceOf would not work for all cases and that is that objects that cross the frame boundaries have their own version of class.
Let's say that you have two pages and one if having the other in an iframe. Let's call them innovatively testParent and testChild. If you create an array instance in testChild like x=new Array(); or x=[];, then the result of x instanceOf Array will be true in testChild, but false in testParent. That's because the Array in one page is different from Array in the other. And, damn it, it makes sense, too. Imagine you did what I did and added a function to the Array class. Would that class be the same as the Array in the iframe, without the function? What if I decide to add
Array.prototype.indexOf?
So, bottom line: in Javascript, instanceOf will not work in any meaningful way across frame boundaries.
Oh, and just so you do have a good way to check if an object is and array, do this:
var strArray=Object.prototype.toString(new Array()); Array.isArray=function(obj) { return Object.prototype.toString(obj)==strArray; }
2 comments:
How can you not "love" javascript... this is one of the many reasons I didn't go to much (or at all) in depth in javrascript (typo intended).
I can't agree with you. I think that the simplicity and flexibility of Javascript have made it a solid and powerful language. Its design is also rather original compared to any other mainstream programming language.
I would say that I prefer Javascript as it is rather than a myriad of proprietary and closed languages that each browser decides to promote or not.
Post a Comment