Javascript Method Invocations
Solution 1:
In JavaScript (for now), this
is determined by how a function is called, not how the function is defined. What Flanagan is saying is that given this:
foo.bar();
...during the call to bar
, this
will refer to the object referenced by foo
.
If you're coming from some other languages like Java or C#, you may think, "But surely this
always refers to foo
within bar
" but that's not the case in JavaScript. Example:
var f = foo.bar; // Get a reference to the function, but not calling it
f(); // Now we call it
In the above, this
within the call to bar
is notfoo
, it's the global object (if you're not in strict mode) or undefined
(if you are).
More (on my blog):
Solution 2:
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) :
var writeHelloFromThis = function() {
console.log('hello from ' + this);
};
writeHelloFromThis();
--> 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 :
var anObject={};
anObject.writeHelloFromThis = writeHelloFromThis;
and now we call writeHelloFromThis with anObject as context :
anObject.writeHelloFromThis();
--> 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 :
var anObjectsWriteHelloFromThis = anObject.writeHelloFromThis;
anObjectsWriteHelloFromThis just stores a function (=a reference) without knowing anything about 'anObject'. So if we call :
anObjectsWriteHelloFromThis();
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 :
writeHelloFromThis.call(anObject);
will have the output "hello from [object Object]", and not windows, since here we force 'this' to be anObject.
Solution 3:
To complement T.J.'s answer, here is an example:
var o = {}; // define an object
o.name = 'foo'; // add an attribute to the objectvar f = function() { // define a functionreturnthis.name; // the function uses this internally
}
o.someFunction = f; // add the function to the objectvar result = o.someFunction();
now the value of result
is 'foo'
because the function has been invoked on the object o, and inside the function, this
refers to the object on which the function has been invoked.
Post a Comment for "Javascript Method Invocations"