-2

jQuery's variable $ for example works both as object and function.

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

How to make variable $ works both as object and function?

$ = function(){} // ???
$ = {}; // ???
Nik
  • 709
  • 4
  • 22

2 Answers2

3

Here, I used variable dollar as $ and implemented it both as object and function.

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

Although you differentiate function and object in the question, in js function is also an object. So you can set any attributes (variables, functions) on another function. Hope you got the answer.

nipunasudha
  • 2,427
  • 2
  • 21
  • 46
1

Javascript function is inherited from Javascript Object.

You can define a function and then add any number of properties on it as well.

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
sbr
  • 644
  • 8
  • 19