Javascript-this Flashcards
What is this in JavaScript?
‘this’ refers to any object related at the moment the function is called.
What does it mean to say that this is an “implicit parameter”?
It is available despite not being declared within function
When is the value of this determined in a function; call time or definition time?
at call time
What does this refer to in the following code snippet?
var character = {
firstName: ‘Mario’,
greet: function () {
var message = ‘It's-a-me, ‘ + this.firstName + ‘!’;
console.log(message);
}
};
the Character object
Given the above character object, what is the result of the following code snippet? Why?
character.greet();
It’s a-me, Mario!
this is referring to the character object, so you’re calling the firstName property of the character object.
Given the above character object, what is the result of the following code snippet? Why?
var hello = character.greet;
hello();
It’s a-me, undefined!
At the moment of call there is no object.
How can you tell what the value of this will be for a particular function or method definition?
look at what object the function with this is contained in.
How can you tell what the value of this is for a particular function or method call?
look to left of the function.