[JavaScript] ‘this’

The “this” object is pretty familiar to the C# developers. It refers to the current object. The “this” keyword is also used in JavaScript but you need to be careful to use it.

1. What does ‘this’ refers to?

You can use the “this” keyword in any functions and it refers to the owner (context) of the function.

function dummy() {
  alert(this); // [object Window]
};
dummy();

In any global function, “this” refers to the global object, which is the “window” object in browsers.

 

2. ‘this’ in Objects

If you define a method in an object, “this” refers to the object itself. “this” can access the object’s other properties and members too.

var adder = {
  x: 1,
  y: 2,
  add: function () {
    alert(this); // [object Object]
    return this.x + this.y;
  }
};

alert(adder.add()); // 3

 

3. Indirect Invocation

Functions can be invoked indirectly with the specified context.

  • apply (thisArg, argsArray)
  • call (thisArg, arg1, arg2, …)
function Add() {
  alert(this); // [object Object]
  return this.x + this.y;
}

var myNum = {
  x: 2,
  y: 3
};

//Add(); // error - x and y are not defined
alert(Add.apply(myNum)); // 5
alert(Add.call(myNum)); // 5

 

4. Changing the Context – bind()

  • function.bind (thisArg)

For a given function, “bind()” creates a new function that has the same function body but the different owner or context.

var adder = {
  x: 1,
  y: 2,
  add: function () {
    return this.x + this.y;
  }
};

var myNum = {
  x: 2,
  y: 3
};

alert(adder.add()); // 3

// bind the method to a different object
var newAdder = adder.add.bind(myNum);
alert(newAdder()); // 5

alert(adder.add()); // still 3

This technique is pretty unique and interesting but can be easily confusing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s