‘this’ keyword, not clear

In Javascript, the value of this is dependent on the way you call the function.

There are 5 ways to call a function in JS, and they all have effect on this:

  1. new Foo(); <= here, you’re creating a new object, and this will reflect that new object
  2. Foo(); <= here, you’re calling the function as-is, and this will be the global object(!)
  3. var obj = { foo: Foo };
    obj.foo();
    <= here, you’re calling the function as a method of obj; this will be obj
  4. Foo.call(thisObject, arg1, arg2); <= here, you can specify the value of this in the first argument
  5. Foo.apply(thisObject, [args]); <= here, you can specify the value of this in the first argument

In 4 and 5, the difference between call and apply is that with call, you need to pass all the arguments separately, whereas with apply, you can pass an array containing all the arguments.

Note that in my example 2 above, the function should have been called foo instead of Foo. Since it’s impossible to know off-hand whether a function is supposed to be called with new or not, the consensus is to start the function name with a capital letter if it’s a constructor (and should be used with new); otherwise, it should start with lowercase.

Leave a Comment