Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使变量$同时作为对象$和函数$()?_Javascript_Jquery - Fatal编程技术网

Javascript 如何使变量$同时作为对象$和函数$()?

Javascript 如何使变量$同时作为对象$和函数$()?,javascript,jquery,Javascript,Jquery,例如,jQuery的变量$既作为对象又作为函数 // You can access object properties such as $.fn; // or $.isReady; // You can also call the function $ such as follows $(); function dollar(a){ console.log(a); } dollar.memberFunc = function(a,b){ console.log(a+b); }

例如,jQuery的变量$既作为对象又作为函数

// You can access object properties such as
$.fn;
// or
$.isReady;
// You can also call the function $ such as follows
$();
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
如何使变量$同时作为对象和函数工作?

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

在这里,我使用变量
dollar
作为
$
,并将其作为对象和函数实现

// You can access object properties such as
$.fn;
// or
$.isReady;
// You can also call the function $ such as follows
$();
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中函数也是一个对象。因此,您可以在另一个函数上设置任何属性(变量、函数)。希望你得到答案。

您可以定义一个函数,然后在其上添加任意数量的属性

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

只需向其添加如下属性:函数$(){…};$。val=5:警报($.val)$();所有函数都是js中的对象,因此您可以向它们添加属性。