In JavaScript you can define functions as object methods.
The following example creates an object (myObject), with two properties (firstName and lastName), and a method (fullName):
Example
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
myObject.fullName(); // Will return "John Doe"
The fullName method is a function. The function belongs to the object. myObject is the owner of the function.
The thing called this
, is the object that "owns" the JavaScript code. In this case the value of this
is myObject.
Test it! Change the fullName method to return the value of this
:
Example
firstName:"John",
lastName: "Doe",
fullName: function () {
return this;
}
}
// This will return [object Object] (the owner object)
myObject.fullName();
Invoking a function as an object method, causes the value of this
to be the object itself.
Invoking a Function with a Function Constructor
If a function invocation is preceded with the new
keyword, it is a constructor invocation.
It looks like you create a new function, but since JavaScript functions are objects you actually create a new object:
Example
function myFunction(arg1, arg2) {
this.firstName = arg1;
this.lastName = arg2;
}
// This creates a new object
const myObj = new myFunction("John", "Doe");
// This will return "John"
myObj.firstName;
A constructor invocation creates a new object. The new object inherits the properties and methods from its constructor.
The this
keyword in the constructor does not have a value.
The value of this
will be the new object created when the function is invoked.
Practice Excercise Practice now