JavaScript Tutorials

Overview

In JavaScript, the “this” keyword is used to refer to various objects. It can be used in different ways to refer to specific types of objects.

  • By itself, “this” refers to the global object
  • In a function, “this” refers to the global object
  • In a function, when used in strict mode, “this” is undefined
  • In an object method, “this” refers to the object
  • In an event, “this” refers to the element that received the event
  • Methods like call(), apply(), and bind() can refer “this” to any object

“this” Referring to the Current Object

When used in an object method, this refers to the object.

const car = {
    type: "Maserati", 
    model: "Quattroporte", 
    color: "white",
    fullName: function() {
        return this; // will return [object Object]
    }
};

“this” in a Method

const car = {
    type: "Maserati", 
    model: "Quattroporte", 
    color: "white",
    fullName: function() {
        return this.type + " " + this.model; // will return Maserati Quattroporte
    }
};

Explicit Function Binding

The call() and apply() methods are predefined JavaScript methods and can be be used to call an object method with another object as the argument.

const myCar1 = {
    type:"Maserati",
    model: "Quattroporte",
    fullName: function() {
    return this.type + " " + this.model;
    }
}

const myCar2 = {
    type:"Alfa Romeo",
    model: "Guilia"
}

myCar1.fullName.call(myCar2); // returns Alfa Romeo Guilia

Function Borrowing

With the bind() method, an object can borrow a method from another object.

const myCar1 = {
    type:"Maserati",
    model: "Quattroporte",
    fullName: function() {
    return this.type + " " + this.model;
    }
}

const myCar2 = {
    type:"Alfa Romeo",
    model: "Guilia"
}

let fullName = myCar1.fullName.bind(myCar2); // variable will be Alfa Romeo Guilia

“this” Precendence

OrderObject
1bind()
2apply()
3call()
4Object method
5Global scope

JavaScript Notes:

  • When using JavaScript, single or double quotation marks are acceptable and work identically to one another; choose whichever you prefer, and stay consistent
  • JavaScript is a case-sensitive language; firstName is NOT the same as firstname
  • JavaScript variables are case sensitive (x is not the same as X)
  • Arrays count starting from zero NOT one; so item 1 is position [0], item 2 is position [1], and item 3 is position [2] … and so on
  • JavaScript variables must begin with a letter, $, or _

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.