javascript this Flashcards
What is this in JavaScript?
the calling object or else the window object
but a better question to ask is “When is this?”.
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 never included in the function’s parameter list or declared with var.
When is the value of this determined in a function; call time or definition time?
at call time
1 )
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);
}
};
2)
Given the above character object, what is the result of the following code snippet? Why?
character.greet();
3)
Given the above character object, what is the result of the following code snippet? Why?
var hello = character.greet;
hello();
1)
“mario”
or, the firstName property of the “character” object
2)
It’s-a-me, Mario!
Because the custom method was called, does not require any arguments, and it used the objects firstName property (this.firstName)
3)
It won’t do anything useful. It will be undefined because no “hello( )” function or method has been defined.
How can you tell what the value of this will be for a particular function or method definition?
right answer:
by looking at the object to the left of the period.
wrong answer:
by simply reading the code. that is the value.
How can you tell what the value of this is for a particular function or method call?
based on code being executed in the code block, and any arguments given (if any required)
what does it mean that something is assigned to the window or something rather?
global window is related to global object.
the answer is if it’s not assigned an object, it’s assigned to the global window