this


In class-based OO languages, this generally references the instance of the class for which the method has been declared, in JavaScript, where functions are first-class objects that aren't declared as part of anything, the object referenced by this -- termed the function context -- is determined not by how the function is declared but by how it's invoked.

This means that the same function can have different contexts depending on how it's called.

Refers to the jQuery object you're currently doing something with.

// this refers to the item under processing in the loop 
    $.each(entries, function() {
      html += '<div class="entry">';
      html += '<h3 class="term">' + this.term + '</h3>';
      html += '<div class="part">' + this.part + '</div>';
      html += '<div class="definition">' + this.definition + '</div>';
      html += '</div>';
    });

The this reference ALWAYS refers to (and holds the value of) an object—a singular object—and it is usually used inside a function or a method. this is used inside a function (let’s say function A) and it contains the value of the object that invokes function A. We need this to access methods and properties of the object that invokes function A, especially since we don’t always know the name of the invoking object, and sometimes there is no name to use to refer to the invoking object. Indeed, this is really just a shortcut reference for the “antecedent object” — the invoking object.

var person = {
        firstName   :"Penelope",
        lastName    :"Barrymore",
        // Since the "this" keyword is used inside the showFullName method below, 
        // and the showFullName method is defined on the person object,​
        // "this" will have the value of the person object because the person object 
        // will invoke showFullName ()​
        showFullName:function () {
        console.log (this.firstName + " " + this.lastName);
        }
    ​
    }
    ​
    person.showFullName (); // Penelope Barrymore
// A very common piece of jQuery code​
    ​
$ ("button").click (function (event) {
   // $(this) will have the value of the button ($("button")) object​
   // because the button object invokes the click () method​
   console.log ($ (this).prop ("name"));
});

// the use of $(this), which is jQuery’s syntax for the this keyword in JavaScript, 
// is used inside an anonymous function, and the anonymous function is executed 
// in the button’s click () method. The reason $(this) is bound to the button object is 
// because the jQuery library binds $(this) to the object that invokes the click method. 
// Therefore, $(this) will have the value of the jQuery button ($(“button”)) object, 
// even though $(this) is defined inside an anonymous function that cannot itself 
// access the “this” variable on the outer function.

Here’s a few very important points to takeaway and remember about the this keyword:

  • Thethiskeyword’s value has nothing to do with the function itself, how the function is called determines the thisvalue
  • It can be dynamic, based on how the function is called
  • You can change the this context through .call(), .apply() and .bind()

this refers to the owner of the function.

  • Object literals Refers to its own object. Window object doesn't invoke the function
    the object does, so this refers to the Object Literal itself.
  • Prototype and Constructor Same as Constructor, this refers to the Constructor
  • Events this points the event owner
  • In a loop

var numbers = [{
  name: 'Mark'
},{
  name: 'Tom'
},{
  name: 'Travis'
}];

// function creates new scope
numbers.forEach(function () {

  console.log(this); // window
});

/*

We could change each iterations's scope to the current 
element's value inside a regular for loop as well 
and use this to access object properties. 

*/

var numbers = [{
  name: 'Mark'
},{
  name: 'Tom'
},{
  name: 'Travis'
}];

for (var i = 0; i < numbers.length; i++) {
  (function () {
    console.log(this.name); // Mark, Tom, Travis
}).call(numbers[i]);
  • setTimeout
var obj = {};
obj.myMethod = function () {
  console.log(this); // this = obj
    setTimeout(function () {
        console.log(this); // window object :O!!!
    }, 100);
};
obj.myMethod();

// How to fix? 

// 1. use .bind()
var obj = {};
obj.myMethod = function () {
  console.log(this); // this = obj
    setTimeout(function () {
        console.log(this); // this = obj
    }.bind(this), 100); // .bind() #ftw
};
obj.myMethod();

// 2. use that = this
var obj = {};
obj.myMethod = function () {
  var that = this; //We can also use the jumping scope trick, var that = this;

  console.log(this); // this = obj
    setTimeout(function () {
        console.log(that); // that (this) = obj
    }, 100);
};
obj.myMethod();

Reference

results matching ""

    No results matching ""