this

  • Revision slug: JavaScript/Reference/Operators/this
  • Revision title: this
  • Revision id: 296379
  • Created:
  • Creator: ethertank
  • Is current revision? No
  • Comment

Revision Content

Introduction

A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.

In general, the object bound to this in the current scope is determined by how the current function was called, it can't be set by assignment during execution, and it can be different each time the function is called. ES5 introduced the bind method to fix a function's this regardless of how it's called.

Global context

In the global context (outside of any function), this refers to the global object, whether in strict mode or not.

console.log(this.document === document); // true

// In web browsers, the window object is also the global object:
console.log(this === window); // true

this.a = 37;
console.log(window.a); // 37

Function context

When the this keyword occurs inside a function, its value depends on how the function is called.

Simple call

function f1(){

Introduction

A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.

In general, the object bound to this in the current scope is determined by how the current function was called, it can't be set by assignment during execution, and it can be different each time the function is called. ES5 introduced the bind method to fix a function's this regardless of how it's called.

Global context

In the global context (outside of any function), this refers to the global object, whether in strict mode or not.

console.log(this.document === document); // true

// In web browsers, the window object is also the global object:
console.log(this === window); // true

this.a = 37;
console.log(window.a); // 37

Function context

When the this keyword occurs inside a function, its value depends on how the function is called.

Simple call

function f1(){
  return this;
}

f1() === window; // global object


function f2(){
  "use strict"; // see strict mode
  return this;
}

f2() === undefined;
Note: In the second example, this should be undefined, because f2 was called without providing any base (e.g. window.f2()). This feature wasn't implemented in some browsers when they first started to support strict mode; because of this, they incorrectly returned the window object.

As an object method

When a function is called as a method of an object, its this is set to the object the method is called on.

In the following example, when o.f() is invoked, inside the function this is bound to the o object.

var o = {
  prop: 37,
  f: function() {
    return this.prop;
  }
};

console.log(o.f()); // logs 37

Note that this behavior is not at all affected by how or where the function was defined. In the previous example, we defined the function inline as the f member during the definition of o.  However, we could have just as easily defined the function first and later attached it to o.f. Doing so results in the same behavior:

var o = {prop: 37};

function independent() {
  return this.prop;
}

o.f = independent;

console.log(o.f()); // logs 37

This demonstrates that it matters only that the function was invoked from the f member of o.

Similarly, the this binding is only affected by the most immediate member reference. In the following example, when we invoke the function, we call it as a method g of the object o.b. This time during execution, this inside the function will refer to o.b. The fact that the object is itself a member of o has no consequence; the most immediate reference is all that matters.

o.b = {g: independent, prop: 42};
console.log(o.b.g()); // logs 42

... on the prototype chain

The same notion holds true for methods defined somewhere on the object's prototype chain. If the method is on an object's prototype chain, this refers to the object the method was called on, as if the method was on the object.

var o = {f:function(){ return this.a + this.b; }};
var p = Object.create(o);
p.a = 1;
p.b = 4;

console.log(p.f()); // 5

In this example, the object assigned to the variable p doesn't have its own f property, it inherits it from its prototype. But it doesn't matter that the lookup for f eventually finds a member with that name on o; the lookup began as a reference to p.f, so this inside the function takes the value of the object referred to as p. That is, since f is called as a method of p, its this refers to p. This is an interesting feature of JavaScript's prototype inheritance.

... or as a getter or setter

Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its this bound to the object from which the property is being set or gotten.

function modulus(){
  return Math.sqrt(this.re * this.re + this.im * this.im);
}

var o = {
  re: 1,
  im: -1,
  get phase(){
    return Math.atan2(this.im, this.re);
  }
};

Object.defineProperty(o, 'modulus', {get: modulus, enumerable:true, configurable:true});

console.log(o.phase, o.modulus); // logs -0.78 1.4142

As a constructor

When a function is used as a constructor (with the new keyword), its this is bound to new object being constructed, unless execution of the constructor results in the JavaScript engine encountering a return statement where the value to be returned is an object.

/*
 * Constructors work like this:
 *
 * function MyConstructor(){
 *   // Actual function body code goes here.  Create properties on |this| as
 *   // desired by assigning to them.  E.g.,
 *   this.fum = "nom";
 *   // et cetera...
 *
 *   // If the function has a return statement that returns an object, that
 *   // object will be the result of the |new| expression.  Otherwise, the
 *   // result of the expression is the object currently bound to |this|
 *   // (i.e., the common case most usually seen).
 * }
 */

function C(){
  this.a = 37;
}

var o = new C();
console.log(o.a); // logs 37


function C2(){
  this.a = 37;
  return {a:38};
}

o = new C2();
console.log(o.a); // logs 38

In the last example (C2), because an object was returned during construction, the new object that this was bound to simply gets discarded. (This essentially makes the statement "this.a = 37;" dead code. It's not exactly dead, because it gets executed, but it can be eliminated with no outside effects.)

call and apply

Where a function uses the this keyword in its body, its value can be bound to a particular object during execution using the call or apply methods that all functions inherit from Function.prototype.

function add(c, d){
  return this.a + this.b + c + d;
}

var o = {a:1, b:3};

// The first parameter is the object to use as 'this', subsequent parameters are passed as 
// arguments in the function call
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16

// The first parameter is the object to use as 'this', the second is an array whose
// members are used as the arguments in the function call
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34

Bound functions

ECMAScript 5 introduced Function.prototype.bind. Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.

function f(){
  return this.a;
}

var g = f.bind({a:"azerty"});
console.log(g()); // azerty

var o = {a:37, f:f, g:g};
console.log(o.f(), o.g()); // 37, azerty

As a DOM event handler

When a function is used as an event handler, its this is set to the element the event fired from (some browsers do not follow this convention for listeners added dynamically with methods other than addEventListener).

// When called as a listener, turns the related element blue
function bluify(e){
  console.log(this === e.currentTarget); // Always true
  console.log(this === e.target);        // true when currentTarget and target are the same object
  this.style.backgroundColor = '#A5D9F3';
}

// Get a list of every element in the document
var elements = document.getElementsByTagName('*');

// Add bluify as a click listener so when the element is clicked on,
// it turns blue
for(var i=0 ; i<elements.length ; i++){
  elements[i].addEventListener('click', bluify, false);
}
return this; } f1() === window; // global object function f2(){ "use strict"; // see strict mode return this; } f2() === undefined;
Note: In the second example, this should be undefined, because f2 was called without providing any base (e.g. window.f2()). This feature wasn't implemented in some browsers when they first started to support strict mode; because of this, they incorrectly returned the window object.

As an object method

When a function is called as a method of an object, its this is set to the object the method is called on.

In the following example, when o.f() is invoked, inside the function this is bound to the o object.

var o = {
  prop: 37,
  f: function() {
    return this.prop;
  }
};

console.log(o.f()); // logs 37

Note that this behavior is not at all affected by how or where the function was defined. In the previous example, we defined the function inline as the f member during the definition of o.  However, we could have just as easily defined the function first and later attached it to o.f. Doing so results in the same behavior:

var o = {prop: 37};

function independent() {
  return this.prop;
}

o.f = independent;

console.log(o.f()); // logs 37

This demonstrates that it matters only that the function was invoked from the f member of o.

Similarly, the this binding is only affected by the most immediate member reference. In the following example, when we invoke the function, we call it as a method g of the object o.b. This time during execution, this inside the function will refer to o.b. The fact that the object is itself a member of o has no consequence; the most immediate reference is all that matters.

o.b = {g: independent, prop: 42};
console.log(o.b.g()); // logs 42

... on the prototype chain

The same notion holds true for methods defined somewhere on the object's prototype chain. If the method is on an object's prototype chain, this refers to the object the method was called on, as if the method was on the object.

var o = {f:function(){ return this.a + this.b; }};
var p = Object.create(o);
p.a = 1;
p.b = 4;

console.log(p.f()); // 5

In this example, the object assigned to the variable p doesn't have its own f property, it inherits it from its prototype. But it doesn't matter that the lookup for f eventually finds a member with that name on o; the lookup began as a reference to p.f, so this inside the function takes the value of the object referred to as p. That is, since f is called as a method of p, its this refers to p. This is an interesting feature of JavaScript's prototype inheritance.

... or as a getter or setter

Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its this bound to the object from which the property is being set or gotten.

function modulus(){
  return Math.sqrt(this.re * this.re + this.im * this.im);
}

var o = {
  re: 1,
  im: -1,
  get phase(){
    return Math.atan2(this.im, this.re);
  }
};

Object.defineProperty(o, 'modulus', {get: modulus, enumerable:true, configurable:true});

console.log(o.phase, o.modulus); // logs -0.78 1.4142

As a constructor

When a function is used as a constructor (with the new keyword), its this is bound to new object being constructed, unless execution of the constructor results in the JavaScript engine encountering a return statement where the value to be returned is an object.

/*
 * Constructors work like this:
 *
 * function MyConstructor(){
 *   // Actual function body code goes here.  Create properties on |this| as
 *   // desired by assigning to them.  E.g.,
 *   this.fum = "nom";
 *   // et cetera...
 *
 *   // If the function has a return statement that returns an object, that
 *   // object will be the result of the |new| expression.  Otherwise, the
 *   // result of the expression is the object currently bound to |this|
 *   // (i.e., the common case most usually seen).
 * }
 */

function C(){
  this.a = 37;
}

var o = new C();
console.log(o.a); // logs 37


function C2(){
  this.a = 37;
  return {a:38};
}

o = new C2();
console.log(o.a); // logs 38

In the last example (C2), because an object was returned during construction, the new object that this was bound to simply gets discarded. (This essentially makes the statement "this.a = 37;" dead code. It's not exactly dead, because it gets executed, but it can be eliminated with no outside effects.)

call and apply

Where a function uses the this keyword in its body, its value can be bound to a particular object during execution using the call or apply methods that all functions inherit from Function.prototype.

function add(c, d){
  return this.a + this.b + c + d;
}

var o = {a:1, b:3};

// The first parameter is the object to use as 'this', subsequent parameters are passed as 
// arguments in the function call
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16

// The first parameter is the object to use as 'this', the second is an array whose
// members are used as the arguments in the function call
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34

Bound functions

ECMAScript 5 introduced Function.prototype.bind. Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.

function f(){
  return this.a;
}

var g = f.bind({a:"azerty"});
console.log(g()); // azerty

var o = {a:37, f:f, g:g};
console.log(o.f(), o.g()); // 37, azerty

As a DOM event handler

When a function is used as an event handler, its this is set to the element the event fired from (some browsers do not follow this convention for listeners added dynamically with methods other than addEventListener).

// When called as a listener, turns the related element blue
function bluify(e){
  console.log(this === e.currentTarget); // Always true
  console.log(this === e.target);        // true when currentTarget and target are the same object
  this.style.backgroundColor = '#A5D9F3';
}

// Get a list of every element in the document
var elements = document.getElementsByTagName('*');

// Add bluify as a click listener so when the element is clicked on,
// it turns blue
for(var i=0 ; i<elements.length ; i++){
  elements[i].addEventListener('click', bluify, false);
}

{{ languages( { "ja": "ja/JavaScript/Reference/Operators/this", "es": "es/Referencia_de_JavaScript_1.5/Operadores/Operadores_especiales/Operador_this", "fr": "fr/JavaScript/Référence_JavaScript/Référence_JavaScript/Opérateurs/Opérateurs_spéciaux/L'opérateur_this", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Operatory/Operatory_specjalne/Operator_this" } ) }}

Revision Source

<h2 id="Introduction">Introduction</h2>
<p>A function's <code>this</code> keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between <a href="/en/JavaScript/Reference/Functions_and_function_scope/Strict_mode" title="en/JavaScript/Strict mode">strict mode</a> and non-strict mode.</p>
<p>In general, the object bound to <code>this</code> in the current scope is determined by how the current function was called, it can't be set by assignment during execution, and it can be different each time the function is called. ES5 introduced the <code><a href="/en/JavaScript/Reference/Global_Objects/Function/bind" title="en/JavaScript/Reference/Global_Objects/Function/bind">bind</a></code> method to <a href="/en/JavaScript/Reference/Operators/this#Bound_functions" title="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/this#Bound_functions">fix a function's <code>this</code> regardless of how it's called</a>.</p>
<h2 id="Global_context">Global context</h2>
<p>In the global context (outside of any function), <code>this</code> refers to the global object, whether in strict mode or not.</p>
<pre class="brush: js">
console.log(this.document === document); // true

// In web browsers, the window object is also the global object:
console.log(this === window); // true

this.a = 37;
console.log(window.a); // 37
</pre>
<h2 id="Function_context">Function context</h2>
<p>When the <code>this</code> keyword occurs inside a function, its value depends on how the function is called.</p>
<h3 id="Simple_call">Simple call</h3>
<pre class="brush: js">
function f1(){<h2 id="Introduction">Introduction</h2>
<p>A function's <code>this</code> keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between <a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/Strict_mode" title="en-US/docs/JavaScript/Strict mode">strict mode</a> and non-strict mode.</p>
<p>In general, the object bound to <code>this</code> in the current scope is determined by how the current function was called, it can't be set by assignment during execution, and it can be different each time the function is called. ES5 introduced the <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" title="en-US/docs/JavaScript/Reference/Global_Objects/Function/bind">bind</a></code> method to <a href="/en-US/docs/JavaScript/Reference/Operators/this#Bound_functions" title="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Special/this#Bound_functions">fix a function's <code>this</code> regardless of how it's called</a>.</p>
<h2 id="Global_context">Global context</h2>
<p>In the global context (outside of any function), <code>this</code> refers to the global object, whether in strict mode or not.</p>

<div style="overflow:hidden;">
<pre class="brush:js">
console.log(this.document === document); // true

// In web browsers, the window object is also the global object:
console.log(this === window); // true

this.a = 37;
console.log(window.a); // 37
</pre>
</div>
<h2 id="Function_context">Function context</h2>
<p>When the <code>this</code> keyword occurs inside a function, its value depends on how the function is called.</p>
<h3 id="Simple_call">Simple call</h3>
<pre class="brush:js">
function f1(){
  return this;
}

f1() === window; // global object


function f2(){
  "use strict"; // see strict mode
  return this;
}

f2() === undefined;
</pre>
<div class="note">
  <strong>Note:</strong> In the second example, <code>this</code> should be <a href="/en-US/docs/JavaScript/Reference/Global_Objects/undefined" title="undefined"><code>undefined</code></a>, because <code>f2</code> was called without providing any base (e.g. <code>window.f2()</code>). This feature wasn't implemented in some browsers when they first started to support <a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/Strict_mode" title="Strict mode">strict mode</a>; because of this, they incorrectly returned the <code>window</code> object.</div>
<h3 id="As_an_object_method">As an object method</h3>
<p>When a function is called as a method of an object, its <code>this</code> is set to the object the method is called on.</p>
<p>In the following example, when <code>o.f()</code> is invoked, inside the function <code>this</code> is bound to the <code>o</code> object.</p>
<pre class="brush:js">
var o = {
  prop: 37,
  f: function() {
    return this.prop;
  }
};

console.log(o.f()); // logs 37
</pre>
<p>Note that this behavior is not at all affected by how or where the function was defined. In the previous example, we defined the function inline as the <code>f</code> member during the definition of <code>o</code>.&nbsp; However, we could have just as easily defined the function first and later attached it to <code>o.f</code>. Doing so results in the same behavior:</p>
<pre class="brush:js">
var o = {prop: 37};

function independent() {
  return this.prop;
}

o.f = independent;

console.log(o.f()); // logs 37
</pre>
<p>This demonstrates that it matters only that the function was invoked from the <code>f</code> member of <code>o</code>.</p>
<p>Similarly, the <code>this</code> binding is only affected by the most immediate member reference. In the following example, when we invoke the function, we call it as a method <code>g</code> of the object <code>o.b</code>. This time during execution, <code>this</code> inside the function will refer to <code>o.b</code>. The fact that the object is itself a member of <code>o</code> has no consequence; the most immediate reference is all that matters.</p>
<pre class="brush:js">
o.b = {g: independent, prop: 42};
console.log(o.b.g()); // logs 42
</pre>

<h4 id="..._on_the_prototype_chain">... on the prototype chain</h4>
<p>The same notion holds true for methods defined somewhere on the object's prototype chain. If the method is on an object's prototype chain, <code>this</code> refers to the object the method was called on, as if the method was on the object.</p>
<pre class="brush:js">
var o = {f:function(){ return this.a + this.b; }};
var p = Object.create(o);
p.a = 1;
p.b = 4;

console.log(p.f()); // 5
</pre>
<p>In this example, the object assigned to the variable <code>p</code> doesn't have its own <code>f</code> property, it inherits it from its <a href="/Prototype" title="Prototype">prototype</a>. But it doesn't matter that the lookup for <code>f</code> eventually finds a member with that name on <code>o</code>; the lookup began as a reference to <code>p.f</code>, so <code>this</code> inside the function takes the value of the object referred to as <code>p</code>. That is, since <code>f</code> is called as a method of <code>p</code>, its <code>this</code> refers to <code>p</code>. This is an interesting feature of JavaScript's prototype inheritance.</p>
<h4 id="..._or_as_a_getter_or_setter">... or as a getter or setter</h4>
<p>Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its <code>this</code> bound to the object from which the property is being set or gotten.</p>
<pre class="brush:js">
function modulus(){
  return Math.sqrt(this.re * this.re + this.im * this.im);
}

var o = {
  re: 1,
  im: -1,
  get phase(){
    return Math.atan2(this.im, this.re);
  }
};

Object.defineProperty(o, 'modulus', {get: modulus, enumerable:true, configurable:true});

console.log(o.phase, o.modulus); // logs -0.78 1.4142
</pre>
<h3 id="As_a_constructor">As a constructor</h3>
<p>When a function is used as a constructor (with the <code><a href="/en-US/docs/JavaScript/Reference/Operators/new" title="new">new</a></code> keyword), its <code>this</code> is bound to new object being constructed, unless execution of the constructor results in the JavaScript engine encountering a return statement where the value to be returned is an object.</p>
<pre class="brush:js">
/*
 * Constructors work like this:
 *
 * function MyConstructor(){
 *   // Actual function body code goes here.  Create properties on |this| as
 *   // desired by assigning to them.  E.g.,
 *   this.fum = "nom";
 *   // et cetera...
 *
 *   // If the function has a return statement that returns an object, that
 *   // object will be the result of the |new| expression.  Otherwise, the
 *   // result of the expression is the object currently bound to |this|
 *   // (i.e., the common case most usually seen).
 * }
 */

function C(){
  this.a = 37;
}

var o = new C();
console.log(o.a); // logs 37


function C2(){
  this.a = 37;
  return {a:38};
}

o = new C2();
console.log(o.a); // logs 38
</pre>
<p>In the last example (<code>C2</code>), because an object was returned during construction, the new object that <code>this</code> was bound to simply gets discarded. (This essentially makes the statement "<code>this.a = 37;</code>" dead code. It's not exactly dead, because it gets executed, but it can be eliminated with no outside effects.)</p>
<h3 id="call_and_apply"><code>call</code> and <code>apply</code></h3>
<p>Where a function uses the <code>this</code> keyword in its body, its value can be bound to a particular object during execution using the <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/call" title="en-US/docs/JavaScript/Reference/Global_Objects/Function/call">call</a></code> or <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply" title="en-US/docs/JavaScript/Reference/Global_Objects/Function/apply">apply</a></code> methods that all functions inherit from <code>Function.prototype</code>.</p>
<pre class="brush:js">
function add(c, d){
  return this.a + this.b + c + d;
}

var o = {a:1, b:3};

// The first parameter is the object to use as 'this', subsequent parameters are passed as 
// arguments in the function call
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16

// The first parameter is the object to use as 'this', the second is an array whose
// members are used as the arguments in the function call
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
</pre>
<h3 id="Bound_functions">Bound functions</h3>
<p>ECMAScript 5 introduced <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" title="en-US/docs/JavaScript/Reference/Global Objects/Function/bind">Function.prototype.bind</a></code>. Calling <code>f.bind(someObject)</code> creates a new function with the same body and scope as <code>f</code>, but where <code>this</code> occurs in the original function, in the new function it is permanently bound to the first argument of <code>bind</code>, regardless of how the function is being used.</p>
<pre class="brush:js">
function f(){
  return this.a;
}

var g = f.bind({a:"azerty"});
console.log(g()); // azerty

var o = {a:37, f:f, g:g};
console.log(o.f(), o.g()); // 37, azerty
</pre>
<h3 id="As_a_DOM_event_handler">As a DOM event handler</h3>
<p>When a function is used as an event handler, its <code>this</code> is set to the element the event fired from (some browsers do not follow this convention for listeners added dynamically with methods other than <code>addEventListener</code>).</p>
<pre class="brush:js">
// When called as a listener, turns the related element blue
function bluify(e){
  console.log(this === e.currentTarget); // Always true
  console.log(this === e.target);        // true when currentTarget and target are the same object
  this.style.backgroundColor = '#A5D9F3';
}

// Get a list of every element in the document
var elements = document.getElementsByTagName('*');

// Add bluify as a click listener so when the element is clicked on,
// it turns blue
for(var i=0 ; i&lt;elements.length ; i++){
  elements[i].addEventListener('click', bluify, false);
}</pre>
  return this;
}

f1() === window; // global object


function f2(){
  "use strict"; // see strict mode
  return this;
}

f2() === undefined;
</pre>
<div class="note">
  <strong>Note:</strong> In the second example, <code>this</code> should be <a href="/en/JavaScript/Reference/Global_Objects/undefined" title="undefined"><code>undefined</code></a>, because <code>f2</code> was called without providing any base (e.g. <code>window.f2()</code>). This feature wasn't implemented in some browsers when they first started to support <a href="/en/JavaScript/Reference/Functions_and_function_scope/Strict_mode" title="Strict mode">strict mode</a>; because of this, they incorrectly returned the <code>window</code> object.</div>
<h3 id="As_an_object_method">As an object method</h3>
<p>When a function is called as a method of an object, its <code>this</code> is set to the object the method is called on.</p>
<p>In the following example, when <code>o.f()</code> is invoked, inside the function <code>this</code> is bound to the <code>o</code> object.</p>
<pre class="brush: js">
var o = {
  prop: 37,
  f: function() {
    return this.prop;
  }
};

console.log(o.f()); // logs 37
</pre>
<p>Note that this behavior is not at all affected by how or where the function was defined. In the previous example, we defined the function inline as the <code>f</code> member during the definition of <code>o</code>.&nbsp; However, we could have just as easily defined the function first and later attached it to <code>o.f</code>. Doing so results in the same behavior:</p>
<pre class="brush: js">
var o = {prop: 37};

function independent() {
  return this.prop;
}

o.f = independent;

console.log(o.f()); // logs 37
</pre>
<p>This demonstrates that it matters only that the function was invoked from the <code>f</code> member of <code>o</code>.</p>
<p>Similarly, the <code>this</code> binding is only affected by the most immediate member reference. In the following example, when we invoke the function, we call it as a method <code>g</code> of the object <code>o.b</code>. This time during execution, <code>this</code> inside the function will refer to <code>o.b</code>. The fact that the object is itself a member of <code>o</code> has no consequence; the most immediate reference is all that matters.</p>
<pre class="brush: js">
o.b = {g: independent, prop: 42};
console.log(o.b.g()); // logs 42
</pre>
<h4 id="..._on_the_prototype_chain">... on the prototype chain</h4>
<p>The same notion holds true for methods defined somewhere on the object's prototype chain. If the method is on an object's prototype chain, <code>this</code> refers to the object the method was called on, as if the method was on the object.</p>
<pre class="brush: js">
var o = {f:function(){ return this.a + this.b; }};
var p = Object.create(o);
p.a = 1;
p.b = 4;

console.log(p.f()); // 5
</pre>
<p>In this example, the object assigned to the variable <code>p</code> doesn't have its own <code>f</code> property, it inherits it from its <a href="/Prototype" title="Prototype">prototype</a>. But it doesn't matter that the lookup for <code>f</code> eventually finds a member with that name on <code>o</code>; the lookup began as a reference to <code>p.f</code>, so <code>this</code> inside the function takes the value of the object referred to as <code>p</code>. That is, since <code>f</code> is called as a method of <code>p</code>, its <code>this</code> refers to <code>p</code>. This is an interesting feature of JavaScript's prototype inheritance.</p>
<h4 id="..._or_as_a_getter_or_setter">... or as a getter or setter</h4>
<p>Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its <code>this</code> bound to the object from which the property is being set or gotten.</p>
<pre class="brush: js">
function modulus(){
  return Math.sqrt(this.re * this.re + this.im * this.im);
}

var o = {
  re: 1,
  im: -1,
  get phase(){
    return Math.atan2(this.im, this.re);
  }
};

Object.defineProperty(o, 'modulus', {get: modulus, enumerable:true, configurable:true});

console.log(o.phase, o.modulus); // logs -0.78 1.4142
</pre>
<h3 id="As_a_constructor">As a constructor</h3>
<p>When a function is used as a constructor (with the <code><a href="/en/JavaScript/Reference/Operators/new" title="new">new</a></code> keyword), its <code>this</code> is bound to new object being constructed, unless execution of the constructor results in the JavaScript engine encountering a return statement where the value to be returned is an object.</p>
<pre class="brush: js">
/*
 * Constructors work like this:
 *
 * function MyConstructor(){
 *   // Actual function body code goes here.  Create properties on |this| as
 *   // desired by assigning to them.  E.g.,
 *   this.fum = "nom";
 *   // et cetera...
 *
 *   // If the function has a return statement that returns an object, that
 *   // object will be the result of the |new| expression.  Otherwise, the
 *   // result of the expression is the object currently bound to |this|
 *   // (i.e., the common case most usually seen).
 * }
 */

function C(){
  this.a = 37;
}

var o = new C();
console.log(o.a); // logs 37


function C2(){
  this.a = 37;
  return {a:38};
}

o = new C2();
console.log(o.a); // logs 38
</pre>
<p>In the last example (<code>C2</code>), because an object was returned during construction, the new object that <code>this</code> was bound to simply gets discarded. (This essentially makes the statement "<code>this.a = 37;</code>" dead code. It's not exactly dead, because it gets executed, but it can be eliminated with no outside effects.)</p>
<h3 id="call_and_apply"><code>call</code> and <code>apply</code></h3>
<p>Where a function uses the <code>this</code> keyword in its body, its value can be bound to a particular object during execution using the <code><a href="/en/JavaScript/Reference/Global_Objects/Function/call" title="en/JavaScript/Reference/Global_Objects/Function/call">call</a></code> or <code><a href="/en/JavaScript/Reference/Global_Objects/Function/apply" title="en/JavaScript/Reference/Global_Objects/Function/apply">apply</a></code> methods that all functions inherit from <code>Function.prototype</code>.</p>
<pre class="brush: js">
function add(c, d){
  return this.a + this.b + c + d;
}

var o = {a:1, b:3};

// The first parameter is the object to use as 'this', subsequent parameters are passed as 
// arguments in the function call
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16

// The first parameter is the object to use as 'this', the second is an array whose
// members are used as the arguments in the function call
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
</pre>
<h3 id="Bound_functions">Bound functions</h3>
<p>ECMAScript 5 introduced <code><a href="/en/JavaScript/Reference/Global_Objects/Function/bind" title="en/JavaScript/Reference/Global Objects/Function/bind">Function.prototype.bind</a></code>. Calling <code>f.bind(someObject)</code> creates a new function with the same body and scope as <code>f</code>, but where <code>this</code> occurs in the original function, in the new function it is permanently bound to the first argument of <code>bind</code>, regardless of how the function is being used.</p>
<pre class="brush: js">
function f(){
  return this.a;
}

var g = f.bind({a:"azerty"});
console.log(g()); // azerty

var o = {a:37, f:f, g:g};
console.log(o.f(), o.g()); // 37, azerty
</pre>
<h3 id="As_a_DOM_event_handler">As a DOM event handler</h3>
<p>When a function is used as an event handler, its <code>this</code> is set to the element the event fired from (some browsers do not follow this convention for listeners added dynamically with methods other than <code>addEventListener</code>).</p>
<pre class="brush: js">
// When called as a listener, turns the related element blue
function bluify(e){
  console.log(this === e.currentTarget); // Always true
  console.log(this === e.target);        // true when currentTarget and target are the same object
  this.style.backgroundColor = '#A5D9F3';
}

// Get a list of every element in the document
var elements = document.getElementsByTagName('*');

// Add bluify as a click listener so when the element is clicked on,
// it turns blue
for(var i=0 ; i&lt;elements.length ; i++){
  elements[i].addEventListener('click', bluify, false);
}
</pre>
<p>{{ languages( { "ja": "ja/JavaScript/Reference/Operators/this", "es": "es/Referencia_de_JavaScript_1.5/Operadores/Operadores_especiales/Operador_this", "fr": "fr/JavaScript/Référence_JavaScript/Référence_JavaScript/Opérateurs/Opérateurs_spéciaux/L'opérateur_this", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Operatory/Operatory_specjalne/Operator_this" } ) }}</p>
Revert to this revision