myFunction.call( [ thisScope ], [ arg1 ], [ arg2 ], [ ... ] ) in ECMAScript 262
Call the function/method, optionally setting a new scope for this
and passing in parameters.
Arguments
name | type | description |
---|---|---|
thisScope | Object |
[optional]
The object to use as thi
|
arg1 | Object |
[optional]
The first argument to pass. |
arg2 | Object |
[optional]
The second argument to pass. |
... | Object | [optional] etc. |
- Return Type
- Object
Description
Like the apply
method, this method of a function object allows you to invoke the function code, while specifying a different scope for it to run in. Unlike that method, parameters to be passed to the called function exist as a comma-separate list, not as an array of parameters.
A real-world example where this can be useful is to simulate multiple interfaces to a single class. (ECMAScript supports hierarchical inheritance amongst user-created classes, but does not allow a single class to inherit from multiple parents.) In the following example, the Rectangle
class wants to be able to call methods from the Polygon
class, but (for no reason other than to illustrate this method) does not inherit from that class.
function Polygon(){ }
Polygon.sweptVolume=function(sweepDistance){
return this.calculateArea()*sweepDistance;
}
function Rectangle(width,length){
this.width=width;
this.length=length;
}
Rectangle.prototype.calculateArea=function(){
return this.width*this.length;
}
var obj1 = new Rectangle(10,5);
var volume = Polygon.sweptVolume.call(obj1,4);
// ** volume is 200