As the book Effective JavaScript put it, “functions are JavaScript’s workhorse”, and one of the reasons I think that’s true is that while other languages resort to different techniques to manipulate data, JS functions alone plays the role of: procedures, methods, constructors, and even classes and modules. So having a deep understanding of JS functions and knowing how to use them effectively in different context will help you master a significant portion of JavaScript.
What’s the difference between Function, Method, and constructor calls in JS?
In other languages that uses OOP we know that functions, methods, and class constructor or three different things, but in JavaScript they are just different patterns of one single construct: functions.
Functions
function serverListen(port){
return `The server is listening at ${port}`;
}```
## Methods
Meanwhile, methods in JavaScript are just functions that happen to be object properties.
```javascript
const server = {
startServer: function(){
try{
serverConnexion(this.databaseName, this.serverPort);
console.log(`The server has started listening on port: ${serverPort}`);
}catch(error){
throw new Error(error);
}
},
databaseName: "auth_db",
serverPort: 4937,
};
server.startServer(); // The server has started listening on port: 4937
javascript
But using the this keyword on a nonmethod function is mostly unnecessary as it it would refer to the global object(or window object):
function runServer(){
return `The server is listening on port: ${this.serverPort}`
}
console.log(runServer()); // The server is listening on port: undefined
Since there is no serverPort
property on the global object it will be set to undefined
.
A good practice in order to quickly catch this kind of mistakes is the use of ES15’s strict mode that sets the default binding of this
to undefined
.
function runServer(){
"use strict"; // 👈
return `The server is listening at port: ${this.serverPort}`
}
console.log(runServer()); // error: cannot read property "serverPort" of undefined
Constructors
Unlike functions a constructor passes a brand-new object as the value of this:
function UserData(password, email){
this.password = password;
this.email = email;
}
const user = new UserData("@#*&*87*#IOI*&^", "will@gmail.com");
user.email; // will@gmail.com
The primary goal of a constructor call is to initialize an object, using the new keyword we are able to return a new Object.
Top comments (0)