Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function in an object/hash

I can call a function directly (I'll use alert as an example) like so

alert("Hello World!");  // pops up an alert window

However, when I put a function in an object, calling it no longer works:

d = {func: alert};
d.func("Hello World!");    // doesn't do anything
d["func"]("Hello World!"); // also doesn't do anything

I figured maybe I needed to explicitly pass in a blank this argument, so I tried

d.func(null, "Hello World!") // still nothing

but to no avail. Interestingly, this does work

d.func.apply(null, ["Hello World!"]);  // success!

but that's so gratuitously verbose it makes my teeth hurt (to quote JWZ). Is there a more concise, less ugly way?

like image 652
Eli Courtwright Avatar asked Mar 01 '23 18:03

Eli Courtwright


2 Answers

Functions in JavaScript are passed by value. The alert() function is natively implemented, meaning it has no JavaScript value. Depending on your browser, the meaninfulness (forgive me for that) of that native wrapper varies. Your code actually works in Google Chrome, but won't work in Firefox, and off the top of my head I'm going to say it won't work in Internet Explorer, either, which is generally not friendly about modifying native objects and functions. You could use the following instead:

d = {
    func: function (message) {
        alert(message);
    }
};
like image 79
Andrew Noyes Avatar answered Mar 12 '23 07:03

Andrew Noyes


If you try this:

function test(x) {
    alert(x);
}
var x = {func: test}
x.func('Hi!');

It works as you expect. When I try doing this to alert directly Firebug gives me the following error message:

[Exception... "Cannot modify properties of a WrappedNative"
nsresult: "0x80570034 (NS_ERROR_XPC_CANT_MODIFY_PROP_ON_WN)"
location: "JS frame :: http://stackoverflow.com/questions/859466/javascript-function-in-an-object-hash :: anonymous :: line 72" data: no]

So I am guessing it's a security thing or something to do with it being a native function.

like image 37
Paolo Bergantino Avatar answered Mar 12 '23 09:03

Paolo Bergantino