Methods
There's another way that JavaScript functions can be invoked...and that's through methods.
Objects
info = {
social: {
youtube: 'https://youtube.com/planetoftheweb',
linkedin: 'https://linkedin.com/in/planetoftheweb',
blog: 'https://raybo.org'
}
}
- The object type
- Function in object
An object is the most flexible data types in JavaScript and they can hold many types of values including functions.
So a method is just a function that has been assigned as a property of an object. Let's take a look at how you define one.
Creating a Method
info = {
social: {...},
logSocial: function(data) {
console.log(`${data.youtube}
${data.linkedin}
${data.blog}`
)
}
}
info.logSocial(info.social);
Assuming that the info object is created as in the previous slide, we can write a function...which is called a method when it's part of an object that logs the value of the different links.
We call the method as part of the object, but it now will perform an action.
The this Keyword
- Object executing code
- Function: global
- Object: object
You can use a special keyword in JavaScript called this.
It refers to the object that is executing the current piece of code.
If you're using this in a regular function, this references the global object.
If you use the this keyword inside a method then it references the object itself.
Using this Keyword
info = {
social: {...},
logSocial: function() {
console.log(`${this.social.youtube}
${this.social.linkedin}
${this.social.blog}`
)
}
}
info.logSocial();
That means that we can rewrite our methods using the this keyword, which references the object.
Let's try this out in CodeSpaces and we'll do a bit of a better job logging our project.
info = {
social: {
youtube: 'https://youtube.com/planetoftheweb',
linkedin: 'https://linkedin.com/in/planetoftheweb',
blog: 'https://raybo.org'
},
logSocial: function() {
for (const key in this.social) {
console.log(`${key}: ${this.social[key]}`);
}
}
}
info.logSocial();
Functions as objects is one of the most useful JavaScript features. You use them all the time, sometimes without even knowing it.
Can you guess which method we've been using extensively in these lessons?
Yep...the console log statemewnt is a method that outputs a message to the web console. Now that you know how to build them, you'll probably notice all types of other methods.