Reputation: 43
I don't get the difference between the last 2 lines, specifically the difference between myFunc.call and myFunc. Can someone please explain to me? I'd really appreciate it.
var myObject = {
length: 400,
};
function myFunc () {
return console.log(this.length);
}
myFunc.call(myObject); // equals 400
myFunc(myObject); // equals zero
Upvotes: 0
Views: 46
Reputation: 6397
.call()
allows you to call a function while specifying what this
will refer to inside the function. Calling it without .call
uses the current value of this
.
In your example, myFunc.call(myObject)
runs myFunc
with myObject
as this
, which allows this.length
to actually refer to something.
Upvotes: 2
Reputation: 700302
The call
method is used to specify a context for the function, the same as if the function was a member of the object, and was called as a method:
var myObject = {
length: 400,
myFunc: function () {
return console.log(this.length);
}
};
myObject.myFunc(); // equals 400
Upvotes: 1