Philip Wallin
Philip Wallin

Reputation: 45

How is it possible for a Javascript function to be undefined and still invokeable?

When I write

window.external.AddSearchProvider

in Internet Explorer 11 I get "undefined", but I can still call and use the function. While in Chrome the method is defined and usable.

If I write

"AddSearchProvider" in window.external

I get "true" in both Internet Explorer and Chrome.

Is this the expected behavior? I was under the impression I could check if I could use a function by checking if it was defined, or is it something I have misunderstood?

Upvotes: 4

Views: 195

Answers (2)

Marc
Marc

Reputation: 3652

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in says

The in operator returns true if the specified property is in the specified object.

Addsearchprovider is a variable in window.external. in checks if there is a variable within window.external with that name. the value of AddSearchProvider doesn't matter

window.external.AddSearchProvider() is a trigger. it triggers all the window.external.AddSearchProvider events that are assigned.

window.external.AddSearchProvider() and window.external.AddSearchProvider are completely different.

Upvotes: -1

Magus
Magus

Reputation: 15124

window.external.AddSearchProvider is not a "plain" javascript function. It's a native function provided by the browser and each browser handle it differently.

When you type window.external.AddSearchProvider in the browser javascript console, you see the representation of this value in the javascript of the browser. Most browser implements a representation of their native function, but it seems like Internet Explorer does not, so you see an undefined because the console has no value to display. But the function is callable.

As a example, you can see it as an object with a method like this

toJavascriptValue : function() {
    return undefined;
}

Upvotes: 2

Related Questions