I am trying to sharpen my JavaScript skills and I am aware that there are four basic ways to invoke a function - which alter the way this
is defined. The two I am interested in are the basic two:
- Invocation as a function
- Invocation as a method
Which is fine. The first, this
will refer to the window
object:
function doSomething() {
console.log(this);
}
doSomething(); // window is logged
And the second this
will refer to the object it is being executed from within:
var t = {
doSomething: function () {
console.log(this);
}
};
t.doSomething(); // t is logged
Which is all fine. However, is it correct to say, that in these two invoking methods, this
is always going to return the object the method is contained within (if that makes sense)?
In the first example, doSomething()
is, in reality, defined within the window
object - so is a property of the window
object, even if we do not define it (or reference it).
Therefore, can it not be said that, in reality, invocation as a function is invocation as a method? Or not?