Reputation: 2699
I have just started learning javascript
and nodejs
by following a tutorial. One of the code they used is:
var express=require('express');
var app=express();
app.listen(3000);
Now when I do:
console.log(typeof app);
console.log(typeof app.listen);
I get:
function
function
as the output. Now if the typeof app
is function
, then how can we use .
operator with it to access some other function(listen
)? I tried to read the express
module but couldn't understand much.
Can anyone give a simple example where we use a function
name with .
operator to access some other function inside it?
I tried this:
var t=function(){
t.bar=function(){
console.log('bar');
}
};
t.bar();
But doesn't work.
Upvotes: 3
Views: 1309
Reputation: 76464
In Javascript, function
s are objects. This is how you can define an object:
var myObject = {/*Some members*/};
This is how you define a function
var myFunction = function(/*Some parameters*/) {/*Do something*/};
typeof myObject
will result in "object"
and
typeof myFunction
will result in "function"
The difference between them is that myFunction
can be called, while myObject
cannot be called. For example this
({})()
will result in an error. However, otherwise they are very similar, they can have members in the same way.
myFunction.myInnerFunction = function(/*Some other parameters*/) {/*Do something else*/};
assigns the myInnerFunction
member of myFunction
a value which happens to be a function
. From there on you will be able to call myFunction.myInnerFunction
. However, you will need to read more about function
s, you may start your study with the this keyword.
Upvotes: 1
Reputation: 1047
Functions are objects, and they can have properties just like any other object.
var t = function() {
console.log('foo');
};
t.bar = function() {
console.log('bar');
};
t.bar();
t.favColor = 'red';
t.shoeSize = 12;
Upvotes: 2
Reputation: 19372
Your question is about basics of language.
There are lots of solutions.
It depends what You want to achieve.
Here are few examples:
const t = () => {};
t.bar = () => {
console.log('bar');
};
t.bar();
or:
const t = {
bar: () => {
console.log('bar');
}
};
t.bar();
or:
class t {
static bar() {
console.log('bar');
}
}
t.bar();
or:
class T {
static bar() {
console.log('bar');
}
}
const t = new T();
t.bar();
and fix on Your example (same as in examples above):
var t = function {};
t.bar = function() {
console.log('bar');
};
t.bar();
Upvotes: 0