Coding with JavaScript For Dummies
Book image
Explore Book Buy On Amazon

Methods are properties with functions for their values. In JavaScript, you define a method the same way that you define any function. The only difference is that a method is assigned to a property of an object. This example demonstrates the creation of an object with several properties, one of which is a method.

var sandwich = {
makeSandwich: function (meat,cheese,bread,condiment) {
 sandwich.meat = meat;
 sandwich.cheese = cheese;
 sandwich.bread = bread;
 sandwich.condiment = condiment;
 var mySandwich = sandwich.bread + ", " + sandwich.meat + 
", " + sandwich.cheese + ", " + sandwich.condiment; return mySandwich; } }

To call the makeSandwich method of the sandwich object, you can then use dot notation just as you would access a property, but with parentheses and parameters supplied after the method name.

 Make me a sandwich


Using this

The this keyword is a shorthand for referencing the containing object of a method. For example, in the code below, every instance of the object name, sandwich, has been replaced with this. When the makeSandwich function is called as a method of the sandwich object, JavaScript understands that this refers to the sandwich object.

 Make a sandwich


The result of using the this keyword instead of the specific object name is exactly the same in this case.

Where this becomes very useful is when you have a function that may apply to multiple different objects. In that case, the this keyword will reference the object that it’s called within, rather than being tied to a specific object.

Constructor functions and inheritance are both enabled by the humble this statement.

About This Article

This article is from the book:

About the book authors:

Chris Minnick is an accomplished author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. Eva Holland is an experienced writer and trainer who has designed and taught online, in-person, and video courses. They are cofounders of WatzThis?

This article can be found in the category: