开发者

does jquery .data return a function

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

$.data(item, "o开发者_运维技巧nlyIfCheckShow")();

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 );
            });
    }


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.


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 + "!");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜