2017-10-14 67 views
-1

jQuery的变量$例如作为对象和功能。

// You can access object properties such as 
$.fn; 
// or 
$.isReady; 
// You can also call the function $ such as follows 
$(); 

如何使变量$既充当对象和功能?

$ = function(){} // ??? 
$ = {}; // ??? 
+1

只需为它添加属性:function $(){...}; $ .val = 5:alert($。val); $(); – user7951676

+2

所有函数都是js中的对象,因此您可以为它们添加属性。 – user7951676

回答

1

在这里,我使用的可变dollar作为$和实现它同时作为对象和功能。

function dollar(a){ 
    console.log(a); 
} 
dollar.memberFunc = function(a,b){ 
    console.log(a+b); 
} 

dollar("Hello"); //as a function 
dollar.memberFunc(10,20); //as a object 

虽然区分函数和对象的问题,但在js函数中也是一个对象。所以你可以在另一个函数上设置任何属性(变量,函数)。希望你能得到答案。

0

Javascript function is inherited from Javascript Object.

您可以定义一个函数,然后添加任何数量上的属性也是如此。

var App = function(){ 
    alert('this is a test'); 
} 
App.version = 0.1; 

App(); // runs the App method 

console.log('app version is ', App.version); // prints the version which is a property of the App function itself