2017 Update
All functions by way of Function.prototype have the .call
method. The reason to use .call()
is to specify what the variable "this
" refers to.
MDN specifies:
The call()
method calls a function with a given this value and
arguments provided individually.
Consider the following:
function x() {
return this;
}
x()
In strict mode x()
returns undefined
in non strict mode it returns the Global object, Window
in a browser context.
Example with .call()
we tell it what "this
" refers to:
function x() {
return this;
}
var obj = {
myName : 'Robert',
myLocation : 'Earth'
}
x.call(obj);
Result: {myName: "Robert", myLocation: "Earth"}
. In the above example we are specifying the obj
object as the value of this
inside the function x()
It can be used to emulate inheritance in OOP.
Example:
var Robert = {
name: "Robert Rocha",
age: 12,
height: "5,1",
sex: "male",
describe: function() {
return "This is me " + this.name + " " + this.age + " " + this.height + " " + this.sex;
}
};
Lets say that the above is a master object(prototype) and you want to inherit the function describe
in another object:
var Richard = {
name: "Richard Sash",
age: 25,
height: "6,4",
sex: "male",
}
The Richard
object does not have the describe function and you want to simply inherit ,so to speak, the function. You would do it like so:
console.log( Robert.describe.call( Richard ) );
Output: This is me Richard Sash 25 6,4 male
call
provides a simple way to solve that issue.