-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(){} // ???
$ = {}; // ???
2
  • 1
    Just add properties to it like: function $(){...}; $.val=5: alert($.val); $(); Commented Oct 14, 2017 at 2:51
  • 2
    All functions are objects in js so you can add properties to them. Commented Oct 14, 2017 at 2:52

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.