Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to invoke a function as a function and method?
In JavaScript, functions can be invoked in different ways. When called directly, it's function invocation. When called as a property of an object, it's method invocation.
Function vs Method Invocation
Function invocation: Calling a function directly by its name.
Method invocation: Calling a function that belongs to an object using dot notation.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Function and Method Invocation</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: green;
margin: 20px 0;
}
.btn {
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
cursor: pointer;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>Invoke a function as function and method</h1>
<div class="result"></div>
<button class="btn">CLICK HERE</button>
<h3>Click on the above button to invoke function as function and method</h3>
<script>
let resEle = document.querySelector(".result");
// Regular function
function add(a, b) {
return a + b;
}
// Object with method
let obj = {
firstName: 'Rohan',
lastName: 'Sharma',
welcome() {
return 'Welcome ' + this.firstName + ' ' + this.lastName;
}
};
document.querySelector(".btn").addEventListener("click", () => {
resEle.innerHTML = 'Function invocation add(2,3): ' + add(2, 3) + '<br>';
resEle.innerHTML += 'Method invocation obj.welcome(): ' + obj.welcome() + '<br>';
});
</script>
</body>
</html>
Output
When you click the button, you'll see:
Function invocation add(2,3): 5 Method invocation obj.welcome(): Welcome Rohan Sharma
Key Differences
| Invocation Type | Syntax | this Context |
|---|---|---|
| Function | functionName() |
undefined (strict mode) or window (non-strict) |
| Method | object.methodName() |
The object that owns the method |
Conclusion
Function invocation calls a standalone function, while method invocation calls a function through an object. The key difference is how the this keyword is bound in each case.
Advertisements
