In the book “JavaScript: The Definitive Guide, 6th edition”, on page 61, section 4.5 Invocation Expressions, it says –
In method invocations, the object or array that is the subject of
the property access becomes the value of thethisparameter while
the function is being executed.
Can someone, in plain english, explain the meaning of that statement, and maybe give an example?
I especially don’t know what is meant by the “subject of the property access” means.
Thanks very much!
My understanding of ‘this’ is that ‘this’ is the context of the function during its execution.
Unless you explicitely change ‘this’, the default behaviour is that the context of the function during its execution is the context of the function call.
First case (most simple) :
–> the output is “hello from [object Window]”, since the context of the call was the global object i.e. Window.
Second case : now we define an object, and add the writeHelloFromThis to it :
and now we call writeHelloFromThis with anObject as context :
–> the output is “hello from [object Object]” : this was the function call’s context : anObject in this case.
3rd case, a little bit trickier : now we will store the writeHelloFromThis of ‘anObject’ into another var :
anObjectsWriteHelloFromThis just stores a function (=a reference) without knowing anything about ‘anObject’. So if we call :
the output will be “hello from [object Window]”, since the context of the call was the global object i.e. Window.
Last remark : if this way of proceeding seems limitative to you, you’re right : that’s why some Function methods : bind, call, apply, allows you to change the context of the function.
so one last example :
will have the output “hello from [object Object]”, and not windows, since here we force ‘this’ to be anObject.