apply()
Function
instance method getterS2C Home
« Globals « Function « apply()
Description
Calls a function with a given this
value and arguments provided as an array.
Syntax
Signature | Description |
---|---|
aFunction.apply(thisArg[, argsArray]) | Calls a function with a given this value and arguments provided as an array. |
Parameters
Parameter | Description |
---|---|
thisArg | The value of this provided for the call to the function. |
argsArray | The arguments with which the function should be called, or null or undefined if no arguments required. |
Examples
Below is an example of using the apply()
method for chaining.
function Country(name, capital) {
this.name = name;
this.capital = capital;
return this;
}
function County(name, capital, county) {
Country.apply(this, arguments);
this.county = county;
}
County.prototype = new Country();
// Define custom override function for County toString().
County.prototype.toString = function CountyToString() {
var county = this.name + ' ' + this.capital + ' ' + this.county;
return county;
}
function Town(name, capital, county, town) {
County.apply(this, arguments);
this.town = town;
}
Town.prototype = new County();
// Define custom override function for Town toString().
Town.prototype.toString = function TownToString() {
var town = this.name + ' ' + this.capital + ' ' +
this.county + ' ' + this.town;
return town;
}
var essex = new County('England', 'London', 'Essex');
alert(essex.toString());
alert(essex.constructor);
var barking = new Town('England', 'London', 'Essex', 'Barking');
alert(barking.toString());
alert(barking.constructor);
Related Tutorials
JavaScript Intermediate Tutorials - Lesson 8 - Functions