473,771 Members | 2,392 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When is a function not a function?

I've got a collection of functions that accept a function or object
(paired with a method name) as a callback.

For the longest time I have relied on this test.

(typeof cb == 'function')

This should work as well, but I am not sure how well it degrades in
older browsers. I think there are issues with functions created in
another context (eg frame) as well.

(cb instanceof Function)

Then I came across this.

(!!fn && typeof fn != "string" && !fn.nodeName && fn.constructor !=
Array && /function/i.test( fn + "" ))

I'm sure it is wrong as it is from jQuery, but it makes me wonder if
there are bugs in older browsers that will mislead my test.

As an aside, I was looking at the jQuery source as some browser
sniffer I was arguing with on a blog cited it as part of an "everybody
is doing it" argument. I had glanced at it previously and dismissed
it based on its resemblance to Prototype. Upon closer inspection, it
makes Prototype look inspired. Suffice to say that anybody who
recommends it hasn't read the code. It's a horror show.

Sep 26 '07
32 3528
Thomas 'PointedEars' Lahn said the following on 10/14/2007 2:00 PM:
Randy Webb wrote:
>Richard Cornford said the following on 10/14/2007 11:18 AM:
>>Randy Webb wrote:
Richard Cornford said the following on 10/13/2007 10:28 PM:
<dh******** **@gmail.comwro te:
>typeof fn? nope, not in safari.
Are you certain? Is it really the case that objects that
return 'function' from a typeof operation cannot be
called? Or are you just not expecting them to be callable?
Have you actually tried calling the objects that safari
asserts are functions?
Can I ask you to first define what you mean by "called"
or "callable"?
No more than sticking an ArgumentsList after a reference to the object
(the 'call operator', with or without arguments). That is what I would
consider calling an object, and to be callable that abject should not
throw an exception as a direct result of its being called (though it may
still throw an exception in response to its arguments'' values, as that
would be behaviour passed the point of calling it and so unrelated to
its callability).
That would imply, to me anyway, that Safari (even in Beta form) gets it
right and all other browsers I tested it on get it wrong. Would that be
a correct assumption?

Not at all. With host objects, all bets are off. And as long as objects
that can't be called do not yield `function' or `object', there is no problem.
Is there any thing in scripting that isn't an Object though? That part
is confusing to me. I thought any and everything was an Object, at least
underneath, and that functions were merely augmented Objects. That
implies to me that anything and everything should return object or some
subset of object.
>>>All other Windows based browsers I have report it as 'object'.
Maybe, but that is neither necessarily true of windows based browsers
nor historically common on Mac browsers. Even Mac IE 5 would report
'function' in this context, and on Windows you only have to go back a
few Opera versions to see the same there.
Then Safari is right and IE/FF/Opera are wrong?

It is not a matter of right and wrong.
Thank you.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javas cript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Oct 14 '07 #21
Randy Webb wrote:
Richard Cornford said the following on 10/14/2007 11:18 AM:
>Randy Webb wrote:
<snip>
>>Can I ask you to first define what you mean by "called"
or "callable"?

No more than sticking an ArgumentsList after a reference to
the object (the 'call operator', with or without arguments).
That is what I would consider calling an object, and to be
callable that abject should not throw an exception as a direct
result of its being called (though it may still throw an
exception in response to its arguments'' values, as that would be
behaviour passed the point of calling it and so
unrelated to its callability).

That would imply, to me anyway, that Safari (even in Beta form)
gets it right
It is more a matter of what safari is doing is not in any way incorrect.
It could do much else instead and still not be doing anything incorrect.
Generally I am inclined to think that when at object can be called it
makes perfect sense for - typeof - to report 'function', even if with
host objects there is nothing to say that they should.
and all other browsers I tested it on get it wrong.
They are not getting it wrong, as there is nothing to define what would
qualify as 'correct' in this context. Some of those browsers are doing
something that is a little irrational in having a callable object but
reporting 'object' with - typeof -, but they either are Windows IE or
are imitating Windows IE in some of its more irrational behaviour.

Remember that on Windows IE all the DOM methods, and functions such as
alert and setTimeout also report 'object' from - typeof -, so it is at
least consistently irrational.
Would that be a correct assumption?
There are no grounds for expecting any particular outcome so there are
no criteria for correct or incorrect.

<snip>
>>All other Windows based browsers I have report it as
'object'.

Maybe, but that is neither necessarily true of windows based
browsers nor historically common on Mac browsers. Even Mac
IE 5 would report 'function' in this context, and on Windows
you only have to go back a few Opera versions to see the same
there.

Then Safari is right and IE/FF/Opera are wrong?
<snip>

On firefox (and all previous Mozilla/gecko browsers) you could not call
the collection objects, so reporting 'object' from - tyepof - is a
rational action. Windows IE is just doing the same as it always has
done, and Opera has recently changed to imitate the behaviour of Windows
IE (previously it did report 'function'). I don't approve of that change
but I can understand why it has happened.

Richard.

Oct 14 '07 #22
Thomas 'PointedEars' Lahn wrote:
Randy Webb wrote:
>and that functions were merely augmented Objects.

Functions/methods are special objects that can be called and inherit from
Object.prototyp e.
D'oh. Make that Function.protot ype.
Oct 14 '07 #23
On Oct 14, 11:18 am, "Richard Cornford" <Rich...@litote s.demon.co.uk>
wrote:
[snip]
>
This is the dojo function:-

| if(dojo.isBrows er && dojo.isSafari){
| // only slow this down w/ gratuitious casting in Safari since
| // it's what's b0rken
| dojo.isFunction = function(/*anything*/ it){
| if((typeof(it) == "function") && (it == "[object NodeList]")){
| return false;
| }
| return (typeof it == "function" || it instanceof Function);
| }
| }else{
| dojo.isFunction = function(/*anything*/ it){
| return (typeof it == "function" || it instanceof Function);
| }
| }
It is useful to note that Dojo (along with jQuery) was cited as an
example of a "major library" that implements browser sniffing, in a
misguided attempt to justify browser sniffing as a viable technique.

Clearly the author(s) have assumed that Safari is the only agent that
is "b0rken" in this way (and that their isSafari method is a reliable
indication of a Safari browser.) As noted, the forks that follow
raise questions about what this code is supposed to do. It also casts
serious doubt about the veracity of functions built atop it.

So the browser sniffer who cited this mess as an example is justifying
his own incompetence by comparing it to other peoples' less-than-
competent output. The fact that lots of developers use these
libraries is cited as proof that they are a worthwhile comparison.
The "argument" is circular as users of jQuery, Dojo, Prototype, etc.
know only what they hear from the "experts" who churn out the
libraries. The "experts" conclude that since so many less-than-expert
developers listen to them, they must be on the right track. Tell
either side they are wrong and they cite the other.

Oct 15 '07 #24
Matt Kruse wrote:
On Oct 14, 9:18 am, Richard Cornford wrote:
>Fist you must state what it is that defined 'a function'. One
completely rational and justifiable definition of 'a function'
in ECMAScritp terms could be "an object that can be called"

Bringing this thread back from the dead...

Is there a way to reliably check whether I can call an object
as a function?
Not if you want to include methods of host objects in the set of objects that could be called.
You might reasonably say that if - typeof x - was 'function' then it would be safe to call the
object, and be correct in all the environments that I have ever encountered. But we both know
that would mean never calling host methods on Windows IE, which would be somewhat disappointing.

<snip>
I know the argument can be made that this is bad design
to not know whether or not you're passing in something
that can be called as a function.
Absolutely.
But I'm asking as a purely technical question, whether or
not it's possible.
Not possible in the general case. Possibly a case fro try-catch and handling the errors. Or
avoid the problem by designing the issue out of the system.

Richard.

Nov 26 '07 #25
VK
On Dec 1, 6:24 pm, VK <schools_r...@y ahoo.comwrote:
1) Report the bug at bugzilla.mozill a.org
No need to do it:

https://bugzilla.mozilla.org/show_bug.cgi?id=296858
and
https://bugzilla.mozilla.org/show_bug.cgi?id=346789
as dups of
https://bugzilla.mozilla.org/show_bug.cgi?id=268945
"Applet tag returns function instead of object with typeof JavaScript
method".

Still a reference to bug ID would be helpful so side readers could
know if one looking for a particular bug workaround or with some
universal JS/DOM feature.
Dec 1 '07 #26
VK
On Dec 1, 9:03 pm, Matt Kruse <m...@mattkruse .comwrote:
else if ( ('ActiveXObject ' in window) &&

This is and always has been a terrible way to infer anything.
Use conditional compilation instead, which will only run in the
JScript engine where the "problems" exist.
Unless someone will implement a browser with conditional compilation
and IE spoofing. :-))

Taking into account the OTC deal of browser producers ("spoof whatever
you need but ActiveXObject") this property check is very reliable as
well - again on condition that someone is trying to use your program
and not to get a runtime error. There is no protection for a
determined user of the latter kind - but he/she never was a subject of
my preoccupations. Within the same OTC deal for IE/Gecko branches it
is pretty secure to:
if ('ActiveXObject ' in window) {
// IE branch
}
else if ('GeckoActiveXO bject' in window) {
// Gecko block
}
else if ('opera' in window) {
// Opera block
}
else {
// some lesser-minor UA
}

Again: no offence of any kind to the conditional compilation instead.
((''+obj).index Of('function')! =-1) ) {
return 'function';
}

This is way to broad. An object like
{ description:'Th is lets you test for a function'}
would be labeled a 'function' by your $typeof function.
Are you sure about it? ;-) Do not mix an object property value with
toString of the object itself.
Dec 1 '07 #27
VK
On Dec 1, 9:31 pm, VK <schools_r...@y ahoo.comwrote:
((''+obj).index Of('function')! =-1) ) {
return 'function';
}
This is way to broad. An object like
{ description:'Th is lets you test for a function'}
would be labeled a 'function' by your $typeof function.

Are you sure about it? ;-) Do not mix an object property value with
toString of the object itself.
What is bad in this block is that it will make unnecessary checks for
JScript objects where typeof always works just fine. Because in IE DOM
model DOM objects have nothing to do with JScript objects the
suggested optimization could be:

else if (('ActiveXObjec t' in window) &&
(!Object.protot ype.isPrototype Of(obj)) &&
((''+obj).index Of('function')! =-1)) {
return 'function';
}
Dec 1 '07 #28
VK
On Dec 2, 12:14 pm, VK <schools_r...@y ahoo.comwrote:
// # Because the problem affects only DOM elements
// # and because DOM elements are strictly separate
// # from JScript objects in IE then to secure ourselves
// # from overloaded toString and from unnecessary checks:

return Object.prototyp e.isPrototypeOf (o) ?
typeof o : /^function/.test(o);
}
}
Oops... The function always returns true/false, not typeof results:

return Object.prototyp e.isPrototypeOf (o) ?
(typeof o == 'function') : /^function/.test(o);
Dec 2 '07 #29
On Dec 2, 3:14 am, VK <schools_r...@y ahoo.comwrote:
return Object.prototyp e.isPrototypeOf (o) ?
...
func += "if (RegExp.prototy pe.isPrototypeO f(o))"+
Fails across windows, yes?

Matt Kruse

Dec 3 '07 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
7827
by: lawrence | last post by:
Suppose I create dynamic web pages with 3 functions (which call other functions to make everything happen, but these 3 you might think of as being the top layer): registerSessions(); sendHtmlToBrowsers(); incrementPageViews(); Is there any chance that incrementPageViews() will be executed? Or, to
7
1391
by: Alan Holloway | last post by:
Hi all, Firstly thanks for your golden insight on my earlier post re bitwise operations. I now have another question! I've just been reading the excellent Peter van der Linden excerpt from sun.com (i'm ordering the book when I get paid), and I am getting to grips with the rules for understanding the complex declarations,
4
3626
by: anonymous | last post by:
Thanks your reply. The article I read is from www.hakin9.org/en/attachments/stackoverflow_en.pdf. And you're right. I don't know it very clearly. And that's why I want to understand it; for it's useful to help me to solve some basic problem which I may not perceive before. I appreciate your help, sincerely.
4
11363
by: Aaron Queenan | last post by:
When I build a C++ library to .NET using the managed C++ compiler, I get the following error message: Linking... LINK : error LNK2020: unresolved token (0A000005) _CrtDbgReport LINK : error LNK2020: unresolved token (0A000007) memset LINK : error LNK2020: unresolved token (0A000008) free LINK : error LNK2020: unresolved token (0A00000A) atexit LINK : error LNK2020: unresolved token (0A000028) wcscpy LINK : error LNK2020: unresolved...
9
4923
by: tshad | last post by:
This is from my previous post, but a different issue. I have the following Javascript routine that opens a popup page, but doesn't seem to work if called from an asp.net button. It seems to work fine from a link. The button does bring up the popup window, but when I press the links on the page, it doesn't return or close the window. ****************************************************************************
5
8631
by: Sakharam Phapale | last post by:
Hi All, I am using an API function, which takes file path as an input. When file path contains special characters (@,#,$,%,&,^, etc), API function gives an error as "Unable to open input file". Same file path containing special characters works fine in one machine, but doesn't work in other. I am using following API function to get short file path. Declare Auto Function GetShortPathName Lib "kernel32" (ByVal lpszLongPath As
1
1977
by: Michael D. Reed | last post by:
I am using the help class to display a simple help file. I generated the help file using Word and saving it as a single page Web page (.mht extension). I show the help file with the following statement. Help.ShowHelp(Parent:=Me, url:=Me.HELP_URL_PRE & Me.myWorker.HelpFile) How do I get it to go away when the program exits? Now when I quit the program that I called it form the help file is sill displayed. Is there a way to get a handle...
1
2070
by: DJG79 | last post by:
Hi all, I am using an open source menu that i found and it works great, except for one thing that when the web page is not scrolled to the very top the drop down links will not stay visible. Has anyone else had this sort of problem with javascript? and any ideas how to fix it would be greatly appreciated.. I have included a copy of the code below, thanks. /**
6
1826
by: Murray Hopkins | last post by:
Hi. THE QUESTION: How do I get a reference to my Object when processing an event handler bound to an html element ? CONTEXT: Sorry if it is a bit long. I am developing a JS calendar tool. One of the requirements is that the calendar will need to display a varying number of months (1..3)
1
3653
anfetienne
by: anfetienne | last post by:
i have this code below that i made....it loads vars from txt file splits it then puts it into an array....once in an array it the brings the pics in from the array to create thumbnails and a larger image. my problem is i have captions to go with it and when i try to load the captions nothing happens or can be seen to be happening. i dont know where i am going wrong as i have no output or compiled errors var locVar = new Array();...
0
9619
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10261
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9911
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8934
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6713
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.