JavaScript this, self, bind, call, and apply

When a function is set and the this value is not assigned, it is always the window object. It can change depending on where the function is invoked.

The quirk is, why does javascript set the this value of a function, within a function within an object to the window object?

How do we deal with it? The self pattern: var self = this;
But before that let’s look at what a function contains.

  1. A function contains properties:
    1. name property (can be anonymous)
    2. code property (invocalble “( )”
  2. Every function also contains three special methods
    1. call
    2. bind
    3. apply

Here is an example of the self pattern.

.bind, .call() and .apply() are accessed by using the dot notation.

.bind creates a copy of the function you are calling, and passes the object you want to be the this property.

With .call() and apply() you are not making a copy – you are invoking the function directly and passing it’s this property with parameters – .apply() requires an array of parameters and .call() requires a list.

Since .bind() is creating a copy of the function, you have some useful patterns at your disposal – function borrowing, and function currying.

Peter Dillon

Development teams seek me out for visual design, reskinning, information hierarchy, usability, iconography, improving task flow, improving the front end build process and more. I specialize in creating engaging solutions to solve real world problems while designing beautiful applications that make the lives of users easier.