javascript-this Flashcards
What is this in JavaScript?
A better question will be when is this, this is an implicit parameter, whose value is determined by when the function is called and not defined
What does it mean to say that this is an “implicit parameter”?
It means it is available in a function’s code block, even though it was not included as a parameter or declared.
When is the value of this determined in a function; call time or definition time?
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 object ‘character’.
Given the above character object, what is the result of the following code snippet? Why?
character.greet();
It’s-a-me, Mario!
.greet() is a method on 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!
the ‘this.firstName’ is bound to the values in ‘character’ which the ‘hello’ variable does not have.
How can you tell what the value of this will be for a particular function or method definition?
The code block it is nested in. If it’s within an object, ‘this’ refers to the object. If it’s within a function declared in the global scope, it refers to the window
How can you tell what the value of this is for a particular function or method call?
This is determined when the function or method is called