For a start, let’s teach the user to say hello:
- let user = {
-
name: "John",
-
age: 30
-
};
-
-
user.sayHi = function() {
-
alert("Hello!");
-
};
-
-
user.sayHi(); // Hello!
Here we’ve just used a Function Expression to create the function and assign it to the property user.sayHi of the object.
Then we can call it. The user can now speak!
A function that is the property of an object is called its method.
So, here we’ve got a method sayHi of the object user.
Of course, we could use a pre-declared function as a method, like this:
-
let user = {
-
// ...
-
};
-
-
// first, declare
-
function sayHi() {
-
alert("Hello!");
-
};
-
-
// then add as a method
-
user.sayHi = sayHi;
-
-
user.sayHi(); // Hello!