0

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?

keldar
  • 6,152
  • 10
  • 52
  • 82
  • 1
    reference: with [`'use strict';`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode) the first example will log [`undefined`](http://jsfiddle.net/Rq3nN/). – Yoshi Mar 04 '14 at 12:28
  • Its just about `this` pointer. If you are declaring a function in `object` then we can say that its a method invocation, because function is now a part of object, which is defined as method. Also,`this` points to object in this case. If you are declaring a function in window(or not inside an object), then its function invocation, because now `this` points to window. – Mohit Pandey Mar 04 '14 at 12:37

1 Answers1

0

Imagine defining your function, not in the scope of the global object like you did, but in the scope of another function:

function outer() {
    var inner = function(){console.log(this)};
    inner();
};
outer();

What do you think the this will be bound to ? What will be printed ?

You might believe it will be the outer function object but its turns out that it will always be the global object.

It is just as if you had written:

function outer() {
    var inner = function(){console.log(this)};
    inner.call(window);
};
outer();

This is a quite hazardous and far from intuitive JS "feature".

So, to get back to your first example, what you are doing is basically this:

doSomething = function () {
    console.log(this);
}
doSomething().call(window);

And, like Yoshi pointed out, if you were using the ES5's strict mode, you would end up doing something like that instead, which is, in my opinion, far less dangerous:

doSomething().call(undefined);

It also gives you a strong hint about the fact that you should never use this in a function ;)