Javascript This Flashcards
What is this in JavaScript?
Find where the function is called and look for an object to the left of the dot. If you can’t see where the function (or method) is called, then you cannot say for sure what the value of this is. current context you are in, could be object or window.
What does it mean to say that this is an “implicit parameter”?
it’s an implicit parameter, meaning that 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?
the value of this is determined 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); } };
still defining the object, so the value of this doesnt exist yet. value is window
Given the above character object, what is the result of the following code snippet? Why?
character.greet();
Its a me mario, object has been defined
Given the above character object, what is the result of the following code snippet? Why? var hello = character.greet; hello();
its a me undefined, because its referring to global window
How can you tell what the value of this will be for a particular function or method definition?
the value of this is determined when the function is called, not when it is defined. By default, when you call a function, it’s this will be given the value of the global window object. you cant tell what it WILL be
How can you tell what the value of this is for a particular function or method call?
It will be the object that is called, or window if no object is called