Skip to content

Instantly share code, notes, and snippets.

@ddlsmurf
Last active May 22, 2021 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddlsmurf/4c4c56e86b6f9a647c7aeec86f90b2cc to your computer and use it in GitHub Desktop.
Save ddlsmurf/4c4c56e86b6f9a647c7aeec86f90b2cc to your computer and use it in GitHub Desktop.
what's `this` in javascript #tutorial

this

Function declarations

There are two (mostly) equivalent ways to define a function:

function Add(a, b) { return a + b };

var Add = function(a, b) { return a + b };

As far as I know the only semantic difference is in the output of Add.toString(), and some browsers fail to recognise the name in the second case and display anonymous function in stack traces.

Function calls

There are 2 main ways to call a function:

Add(1, 2);

In this case, no context is provided, so when Add is running, this will be the default context. This is usually window or similar but varies on implementation and ECMA strictness/version. Do not rely on this in Add

And these two equivalent methods:

Add.call (something,  1, 2);
Add.apply(something, [1, 2]);

When Add runs in both calls, this will be the value of something.

If something is null or undefined, depending on the strictness etc, it may be window or similar, or null. Do not rely on this in Add

"Method" calls

When a function is a property of an object, a short-hand call me be used:

var Obj = { };
Obj['Add'] = Add;

Obj.Add   (1, 2);
Obj['Add'](1, 2);

var name = 'Add';
Obj[name] (1, 2);

With both syntaxes, when Add is running, this will point to Obj.

This may be overriden, for instance since the following is not a shorthand call (such as O.F() or O[F]()), something is the value used:

Obj.Add.call(something, 1, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment