JavaScript Function Call
- Previous Page JS Function Call
- Next Page JS Function Apply
method reuse
Using call()
methods, you can write methods that can be used on different objects.
Functions are object methods
In JavaScript, functions are object methods.
If a function is not a method of a JavaScript object, then it is a function of the global object (see the previous chapter).
The following example creates an object with three properties (firstName
,lastName
,fullName
).
Example
var person = { firstName: "Bill", lastName: "Gates", fullName: function () { return this.firstName + " " + this.lastName; {} {} person.fullName(); // It will return "Bill Gates"
The fullName property is amethod.The person object is the methodowner.
The fullName property belongs to person object's method.
JavaScript call() method
call()
Methods are predefined JavaScript methods.
It can be used to call methods of the owner object as a parameter.
By call()
, you can use methods belonging to another object.
This example calls the fullName method of person and uses it for person1:
Example
var person = { fullName: function() { return this.firstName + " " + this.lastName; {} {} var person1 = { firstName: "Bill", lastName: "Gates", {} var person2 = { firstName: "Steve", lastName: "Jobs", {} person.fullName.call(person1); // It will return "Bill Gates"
This example calls the fullName method of person and uses it for person2:
Example
var person = { fullName: function() { return this.firstName + " " + this.lastName; {} {} var person1 = { firstName: "Bill", lastName: "Gates", {} var person2 = { firstName: "Steve", lastName: "Jobs", {} person.fullName.call(person2); // It will return "Steve Jobs"
Call() method with parameters
The call() method can accept parameters:
Example
var person = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + city + "," + country; {} {} var person1 = { firstName: "Bill", lastName: "Gates" {} person.fullName.call(person1, "Seattle", "USA");
- Previous Page JS Function Call
- Next Page JS Function Apply