0

Can somebody explain the this keyword in Javascript? Preferably in plain english without quoting online sources or textbook. I'm pretty sure I read through those already. I still haven't quite grasped the concept yet.

I understand that this can have several different meanings, depending on how and when it's used.

For instance, I read it could refer to the global object in some cases. Can you explain the different situations where the meaning of this would change and how it's used?

TTT
  • 21
  • 3
  • 1
    http://stackoverflow.com/questions/14661108/javascript-method-invocations/14661341#14661341 – GameAlchemist Feb 17 '13 at 08:00
  • @AndyRay you can't do anything. it is not closed so i ans. it. – Arpit Feb 17 '13 at 08:00
  • Sorry, I'm new to Stackoverflow. Why was my question voted down? – TTT Feb 17 '13 at 08:06
  • It seems to be a duplicate of another question (see comment above yours). I'm more curious why my answer was voted down, which is a perfectly reasonable answer whether or not the question is duplicate or not. – Joe Feb 17 '13 at 08:07
  • Actually, this is even closer, and perhaps more useful for you: [JavaScript "this" keyword](http://stackoverflow.com/questions/3127429/javascript-this-keyword) – Joe Feb 17 '13 at 08:11

2 Answers2

0

A better way to look at this is "How are functions called in Javascript?"

Internally there is a function primitive known as "[[Call]]" that we have an interface to in Function.prototype.call(thisArg, arguments...) so that's what I'll use here.

Every time you call a function in Javascript you're writing syntax that will convert to an equivalent Function.call statement, and it's passing in that thisArg for you. It depends purely on the way you call the function and not on any other object oriented concepts. This is one of the main confusions programmers used to the way class-based object semantics work in other languages have when they come to Javascript.

In the case of a function called in the global context:

function foo(a) { console.log(a); return this; }
foo(5); // equivalent to foo.call(window, 5);
        // outputs 5, returns (Window)

In the case of a function called as if it were linked to an object (dot syntax):

var o = { foo: function(a) { console.log(a); return this; } };
o.foo(5); // equivalent to o["foo"].call(o, 5)
          // outputs 5, returns (Object(o))

That's really all there is to it. Notice that we can get to the same function a different way:

var x = o.foo;
x(5); // equivalent to x.call(window, 5);
      // outputs 5, returns (Window)

and this exact same function has no knowledge of being related in any way at all to the o we created it with.

In as plain English as I think this topic can get:

  • If you call a function without putting a dot in front, this will be window (the global object).
  • If a dot is in front, this will be the object in front of the dot.

If you don't like the way this works, you can simulate different behavior in a variety of ways (like Function.prototype.bind or passing your own thisArg into call or apply).

Small print: In ECMAScript strict mode, where window is passed in the examples above, it instead will pass undefined. And by "dot in front" I'm just speaking practically, o["foo"](6), being the same as o.foo(6) does the same thing with this.

Plynx
  • 11,041
  • 3
  • 30
  • 33
-1

To understand this you have to understand object oriented programming.

In object oriented programming, most methods (functions) belong to objects. In Javascript, most objects are window elements; a button, a list, a div. Almost anything on your web page that you can describe as a noun is probably an object, in some fashion; and the few things that aren't, are members of objects.

So, in object oriented programming, you have the problem that you might have a method, say, onclick. Inside onclick you have some code that executes; let's say you are changing the background of a <div> from blue to green and back when it is clicked on. Let's construct that, in english/pseudocode.

myDiv.onClick {
  if the div that was clicked on has a background of blue then set that div's background to green
  else if the div that was clicked on has a background of green then set it to blue
}

So, pretty easy, right? If this weren't object oriented programming, your function would take an argument, div_id. So,

onClick(div_id theDiv) {
  if theDiv.background=blue then theDiv.background=green
  else if theDiv.background=green then theDiv.backgrond=blue
}

However, this is object oriented programming. onClick is a method of the div, and part of the advantage of object oriented programming is that you don't need to pass arguments like which div you mean - the div you mean is the one whose argument was called, of course! Each div has its own reference to onClick, possibly its own copy depending on how you wrote the method.

That does leave a problem, though. How do you say,

  if this Div's background is blue then set this div's background to green

? The answer is this. this refers to the object that the current method belongs to. So, when a div is clicked on, its onClick method is called; and you have:

div.onClick() {
  if this.background=blue then this.background=green
  else if this.background=green then this.background=blue
}

So you only write one div.onClick function, and now every div is able to be turned blue or green at your leisure.

Joe
  • 58,871
  • 5
  • 42
  • 60