Javascript-this Flashcards
What is ‘this’ in JavaScript?
‘this’ is an implicit parameter of all JavaScript functions.
What does it mean to say that ‘this’ is an “implicit parameter”?
It is available in a function’s code block even though it was never included in the function’s parameters list or declared with ‘var’.
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); } };
Do not know yet. The value of ‘this’ can only be determined during call time (not during a function definition).
Given the above character object, what is the result of the following code snippet? Why?
character.greet();
Result = “It’s-a-me, Mario!” because ‘this’ refers to the object being called. The object firstName property has the value of Mario.
Given the above character object, what is the result of the following code snippet? Why? var hello = character.greet; hello();
Result = “It’s-a-me, undefined!” because ‘this’ refers to the window (hello is not a property of an object, therefore default object would be the window object). Window object does not have the property firstName so therefore, ‘this.firstName” has the value of undefined.
How can you tell what the value of ‘this’ will be for a particular function or method definition?
You can’t. Value of ‘this’ is determined at call time.
How can you tell what the value of ‘this’ is for a particular function or method call?
By looking to left of the dot (the object).