- Building Applications with Spring 5 and Vue.js 2
- James J. Ye
- 350字
- 2025-04-04 16:05:51
Functions and methods
A function in JavaScript is quite different from a method in Java because it is actually an object created by the Function constructor, which is a built-in object of the language. Yes, that's right. Function itself is an object too. What is a method in JavaScript, then? When a function is a property of an object, it is a method. So, in JavaScript, a method is a function, but not all functions are methods.
Since a function is an object, it can also have properties and methods. To establish whether an object is a function or not, you can use instanceof, as follows:
var workout = function () {};
console.log(workout instanceof Function); // true
What is the difference between a function and other objects in JavaScript, apart from the fact that it is created by the Function constructor? First of all, a function is callable, while other objects are not. Another difference is that a function has a prototype property while other objects don't. We will talk about prototype later.
In JavaScript, you can use a function to create objects with new. In a case such as this, that function serves as a constructor. As a convention, when a function serves as a constructor, it should be capitalized. The following is a simple example of using a function as a User constructor. We will build the User constructor containing more details later:
function User () {
}
var user = new User();
Before we move on, let's see the different ways to create a function in JavaScript. Function declarations and function expressions are the most common ways to create functions. Other than that, you can use new Function() to create a function. However, this is not recommended due to its poor performance as well as its readability. The User function in the preceding code snippet is a function declaration. And workout is a function expression. The way that a function is created and invoked will affect the execution context that its function body will point to. We will talk about it later.