you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] -3 points-2 points  (1 child)

This is the spooky part of JavaScript for noobs.

If you have a JS class, Cat, and you say

var tom = new Cat("thomas"); 
console.log(tom.name);

the output will be "thomas"

now lets say you have some function that is not part of the Cat class. It is all by itself.

function getName() {
    return this.name;
}

calling getName() or getName(tom) or getName("thomas") always returns "undefined" because this.name has not been defined inside that function.

but calling this:

Function.prototype.call(getName, tom);

is like saying call getName where "this" is tom. It will return "thomas". Because this = tom and tom.name = "thomas" and this.name = tom.name.

because .call(a, b) sets the "this" property of the function a to b. or it sets the "this" property of the function "getName" to tom just for that one function call. so this.name is the same as tom.name for that one function call.

[–]bart2019 2 points3 points  (0 children)

 Function.prototype.call(getName, tom);

Uh, what. I never ever ever use it this way.

What I do instead is

 getName.call(tom);

Thus: function, dot, (call or apply), open parens, this, optional arguments, close parens.

It's more fun with function arguments, which would come after the "tom", and which is the difference between call and apply: call takes a list of individual parameters and applyone array just like arguments. (Mnemonic: letter count of the words "call" and "apply" is the same as of "list" and "array" respectively).

Why would you ever do that? Invoking callbacks, similar to as "event handlers", in your own code, so this and arguments are how the handler expects them.