JavaScript: Functions in Objects
In the same way that objects can contains variables, they can also contain functions. This is essentially why you can call the string methods such as aString.toUpperCase(). Functions that are part of an object act in almost the same way as regular functions, except for a few differences that are explained below.
Setting Object Functions
Once you have an object in your code, you are able to add functions to that code using the same dot operator that you use to access variables on an object. The syntax is essentially the same as declaring regular functions, only you assign the function to a property using the “=” sign, like setting a variable on an object. For instance;
var myObject = {}
myObject.sayHello = function {
console.log("Hello");
}Calling Object Functions
Once you have added a function to an object, calling it is just the same as calling methods on a string. Using the object name followed by a dot allows you to ‘open the box’ and get at the values/functions inside. Once you have done this, you can call the function like any other function.
var myObject = {}
myObject.sayHello = function {
console.log("Hello");
}
myObject.sayHello();this
There is one other major difference when you have attached a function to an object. When you call that function, JavaScript makes available a special property called ‘this’. You can use the word ‘this’ to refer to the object that owns this function. This gives the function a way of acting on data within the object.
For example, this code creates a counter object. The counter object has 1 data property called value and 2 functions called increment and log. The increment function adds one to the counter stored in the object and log prints it to the console.
var counter = {
value: 0
}
counter.increment = function() {
this.value += 1;
}
counter.log = function() {
console.log( this.value );
}You can then use this object throughout your code like this;
counter.increment();
counter.increment();
counter.print(); // Should print '2'Again, notice how this is just the same as accessing functions on strings - only they are functions you have made yourself!
Summary
The main differences to normal functions are;
- You must assign the function to be a part of an existing object.
- You must use the object name, followed by a dot, and then the function name, to call the function.
- The function will have access to the special variable ‘this’ which refers to the object it is part of.
You can think of Strings and Arrays as objects in a sense - they are objects which contain data and provide a host of functions that you can call to manipulate the data inside of them. This is just one way that we can go about making our own objects like strings and variables.