Learn JavaScript in Construct, part 8: object methods

25

Index

Stats

6,480 visits, 14,428 views

Tools

Translations

This tutorial hasn't been translated.

License

This tutorial is licensed under CC BY-NC 4.0. Please refer to the license text if you wish to reuse, share or remix the content contained within this tutorial.

Published on 5 Nov, 2021. Last updated 16 Dec, 2021

This is part 8 of the tutorial series Learn JavaScript in Construct. This part continues on from part 7. So in case you missed it, see Learn JavaScript in Construct, part 7: Objects.

In this part we'll continue using an empty script file in a new Construct project as we've done for the past few tutorials. We've previously covered functions and objects separately, but they have some interesting and useful special features when combined, which this part covers.

Methods

An object can have a function for one of its properties. The example below shows an object with a property logMessage which is a function.

let person = {
	name: "Joe",

	logMessage: function()
	{
		console.log("Hello world!");
	}
};

// Logs "Hello world!" to the console
person.logMessage();

Notice how we're combining several things we've learnt so far:

  • There's an object with a property named logMessage
  • That property has a value that is a function (using a function expression)
  • The property is accessed with a dot, and the function called with (), so the line person.logMessage() calls the function stored in the logMessage property of the object person

Functions that are used like this are also referred to as methods. This is just another name for a function that is associated with an object.

Shorthand syntax

The previous example can also be written with a shorthand syntax for the logMessage method, omitting the colon and function keyword. This works exactly the same as before, it just provides a shorter way to write it.

let person = {
	name: "Joe",
	
	// Shorthand syntax for method
	logMessage()
	{
		console.log("Hello world!");
	}
};

person.logMessage();

this

Suppose we want to change the logMessage method to logName and have it include the name property of the object in the logged message. One way to do this would be to refer to person.name in the method. This would work, but the method would be tied to the specific person variable the object is stored in. Objects can be assigned to different variables, passed as function parameters, and so on. So we actually want a way to say "the name property of the object the method was called on".

JavaScript provides the this keyword to do that. It refers to the object the method was called on. The example below demonstrates a logName method using this.

let person = {
	name: "Joe",
	
	logName()
	{
		console.log(`The person's name is ${this.name}`);
	}
};

// Logs "The person's name is Joe"
person.logName();

In other words, calling obj.method() will call the function method() with this referring to obj.

Now we have a way to create objects with both data properties and methods that use those data properties. This is referred to as Object Oriented Programming, or OOP.

this can actually be used in any function, and it still refers to the object to the left of the dot when it is called. The next example demonstrates how this is used in a normal function, and when added as a property of an object and called, it still refers to the object it was called on.

// Note the logName function uses 'this'
function logName()
{
	console.log(`The person's name is ${this.name}`);
}

let person1 = {
	name: "Joe"
};

let person2 = {
	name: "Tom"
};

// Add the logName function as properties of both objects
person1.logName = logName;
person2.logName = logName;

// Logs: "The person's name is Joe"
person1.logName();

// Logs: "The person's name is Tom"
person2.logName();

Note in the above example, both logName properties refer to the same function. However each time it is called this refers to a different object, because there is a different object to the left of the dot when it's called.

'this' without an object

What if you call a function using this without an object? It will be undefined, since there is no associated object.

function logThis()
{
	console.log(`'this' is ${this}`);
}

// Logs: 'this' is undefined
logThis();

Notice with our previous example using logName, this would cause an error, as you cannot read properties off anything nullish (null or undefined).

function logName()
{
	console.log(`The person's name is ${this.name}`);
}

// TypeError: Cannot read properties of undefined (reading 'name')
logName();

Similarly while you can write code using this outside of a function, it will also be undefined.

console.log(this);	// undefined

In other words, this is only really useful inside object methods to refer to the object that the method was called on. Outside of that it's generally undefined. There are other ways that this can be used in JavaScript, such as other ways to call functions while specifying what this should refer to, but they're more advanced cases that we won't cover here.

Next Tutorial In Course

Learn JavaScript in Construct, part 9: Data structures 19:43

Learn about some fundamental programming data structures and how they are used in JavaScript: arrays, maps and sets.

  • 2 Comments

  • Order by
Want to leave a comment? Login or Register an account!