Back to Blog

Understanding this in Javascript object literal

on August 6, 2009

Here is code.

1var foo = {
2  first: function () {
3    console.log("I am first");
4  },
5
6  second: function () {
7    console.log("I am second");
8  },
9};
10
11foo.first();
12foo.second();

Everything works fine.

Now there is a need for function second to call function first. Try this and it will fail.

1var foo = {
2  first: function () {
3    console.log("I am first");
4  },
5
6  second: function () {
7    console.log("I am second");
8    first();
9  },
10};
11
12foo.second();

One way to fix this problem is to hardcode value foo inside the second function. Following code works.

1var foo = {
2  first: function () {
3    console.log("I am first");
4  },
5
6  second: function () {
7    console.log("I am second");
8    foo.first();
9  },
10};
11
12foo.second();

Above code works but hardcoding the value of foo inside the object literal is not good. A better way would be to replace the hardcoded name with this .

1var foo = {
2  first: function () {
3    console.log("I am first");
4  },
5
6  second: function () {
7    console.log("I am second");
8    this.first();
9  },
10};
11
12foo.second();

All is good.

Chasing this

Javascript allows one to create function inside a function. Now I am changing the implementation of method second. Now this method would return another function.

1var foo = {
2  first: function () {
3    console.log("I am first");
4  },
5
6  second: function () {
7    return function () {
8      this.first();
9    };
10  },
11};
12
13foo.second()();

Also note that in order to invoke the returned function I have double ()() at the end.

Above code does not work. It did not work because this has changed. Now this in second function refers to the global object rather than referring to the foo object.

Fix is simple. In the function second store the value of this in a temporary variable and the inner function should use that temporary variable. This solution will work because of Javascript's inherent support for closure.

1var foo = {
2  first: function () {
3    console.log("I am first");
4  },
5
6  second: function () {
7    var self = this;
8    return function () {
9      self.first();
10    };
11  },
12};
13
14foo.second()();

You might also like

If you liked this blog post, check out similar ones from BigBinary