1

I am pretty new to JavaScript, and I've just started working with .apply() and other methods that use the keyword this, and I can tell that this has something to do with the context in which the function is invoked, but I'd really like to understand what exactly this is referring to.

The relationship between a particular function invocation and this looks similar to the relationship between an object and a property/method.

Are these two relationships related in anyway?

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
EMC
  • 846
  • 1
  • 6
  • 21
  • `value of the object that invokes the function where this is used.` – Holybreath Feb 26 '14 at 16:23
  • [This](http://stackoverflow.com/questions/3127429/javascript-this-keyword) would help you. – Rajesh Dhiman Feb 26 '14 at 16:27
  • as objects, functions can have attributes. Inside a function, "this" refers to the function that's currently running. So if a function has a "var a = 1", then "this.a" equals 1. That's a pointless example, but "this" is also an important part of visibility and scoping in javascript. – sea-rob Feb 26 '14 at 16:29
  • Have a look at the [MDN documentation about `this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this). – Felix Kling Feb 26 '14 at 16:33
  • @thatidiotguy: Uh what? There are many objects that are *not* functions. – Felix Kling Feb 26 '14 at 16:34

2 Answers2

1

According to the ECMAScript Language Specification Section 11.1.1 the answer is

The this keyword evaluates to the value of the ThisBinding of the current execution context.

Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
1

Here are three cases, which you can consider. The are not described formally but instead simple and intuitive:

Default context

If you don't specify the context and invoke a function (not method), this will be the global object:

function foo() {
  console.log(this); //window
}

Set context implicitly

If you invoke a function, which is method of given object this will be the object before the last dot:

function foo() {
  console.log(this);
}

var bar = {};
bar.foo = foo;
bar.foo(); //bar
bar.baz = {};
bar.baz.foobar = foo;
bar.baz.foobar(); //bar.baz

Set context explicitly

You can change the context using call, apply, bind:

function foo() {
  console.log(this);
}

foo.call(1); //1
foo.call(window); //window

var bar = {};
bar.foo = foo;
bar.foo.apply(42); //42
Minko Gechev
  • 23,174
  • 7
  • 57
  • 66