2011-05-09 66 views
0

我正在处理一位旧程序员留下的代码。他用是否jQuery .data返回函数

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

,我想知道如果jquery.data甚至返回的功能。这似乎很奇怪。 下面是数据代码直接从拉的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); 
      }); 
    } 
+0

下面是关于如何'jQuery.data()'作品的解释:http://stackoverflow.com/questions/ 2764619/how-do-jquery-data-work – KushalP 2011-05-09 18:58:25

+0

还有几个问题[(1)](http://stackoverflow.com/questions/3168733/where-does-jquery-datas-method-informatio n-go),[(2)](http://stackoverflow.com/questions/4384784/jquery-data-storage)关于'jQuery.data'如何工作。 – Anurag 2011-05-09 19:53:23

回答

4

一个简单的练习

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

$([document.body]).data('func')(); 
在ECMA-262

(JavaScript)的变量是对象,函数是另一种对象,如String,Number,Array ...变量可以是没有问题的对象,并且语言的灵活性可以让你做类似的事情。

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

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

希望这会有用,祝你有美好的一天。

0

正如falcacibar所说,在Javascript(ECMAScript)中函数是对象。这意味着你可以指定一个作为一种价值,像这样(使用jQuery's data function):

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

话虽这么说,你可以看到一个变量,使用什么类型的对象的内置typeof运营商,这可能是有用的如果你想使用一个非函数对象的()操作时,能够防止错误:

if (typeof myObject === 'function') { 
    myObject(); 
} else { 
    console.log("ERROR: myObject is not a function, it's a " + typeof myObject + "!"); 
}