0

I am working in some code that was left behind by an old programmer. He uses

$.data(item, "onlyIfCheckShow")();

and I am wondering if jquery.data even returns a function. It seems quite odd. Below is the data code pulled directly from the jquery.js:

data: function( key, value ){
        var parts = key.split(".");
        parts[1] = parts[1] ? "." + parts[1] : "";

        if ( value == null ) {
            var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);

            if ( data == undefined && this.length )
                data = jQuery.data( this[0], key );

            return data == null && parts[1] ?
                this.data( parts[0] ) :
                data;
        } else
            return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){
                jQuery.data( this, key, value );
            });
    }
namuol
  • 9,816
  • 6
  • 41
  • 54
  • Here's an explanation on how `jQuery.data()` works: http://stackoverflow.com/questions/2764619/how-does-jquery-data-work – KushalP May 09 '11 at 18:58
  • Few more questions [(1)](http://stackoverflow.com/questions/3168733/where-does-jquery-datas-method-information-go), [(2)](http://stackoverflow.com/questions/4384784/jquery-data-storage) regarding how `jQuery.data` works. – Anurag May 09 '11 at 19:53

2 Answers2

4

a simple exercise

$([document.body]).data('func', function(){ 
    return alert("passed"); 
});

$([document.body]).data('func')();

in the ECMA-262 (Javascript) variables are objects, and a function is another kind of object, like String, Number, Array... a variable could be an object without problems, and the flexibility of the language could let you do things like.

var funcarray = function() {
    return ['one','two','three'];
}

funcarray()[2]; // will be "three"

hope this be useful, have a nice day.

Felipe Buccioni
  • 19,109
  • 2
  • 28
  • 28
0

As falcacibar said, in Javascript (ECMAScript) functions are objects. This means you can assign one as a value, like so (using jQuery's data function):

var func = function () { alert("Hello!"); };
$.data(item, "onlyIfCheckShow", func);

That being said, you can see what type of object a variable is using the built-in typeof operator, which can be useful if you're trying to prevent errors when using the () operator on a non-function object:

if (typeof myObject === 'function') {
    myObject();
} else {
    console.log("ERROR: myObject is not a function, it's a " + typeof myObject + "!");
}
namuol
  • 9,816
  • 6
  • 41
  • 54