L

JavaScript Notes

This Keyword

The "this" keyword refers to the object that is currently executing the code.

Student Example

Consider the following JavaScript object:

const student = {
    name: "shradha",
    age: 23,
    eng: 95,
    math: 93,
    phy: 97,
    getAvg() {
        let avg = (this.eng + this.math + this.phy) / 3;
        console.log(`${this.name} got avg marks = ${avg}`);
    }
}
  • In the initial attempt to calculate the average, eng, math, and phy were accessed directly, leading to a ReferenceError because the code couldn't find these variables in the current scope.

  • The corrected code uses this.eng, this.math, and this.phy to correctly access the object's properties.

    • this refers to the student object, allowing the getAvg function to access the correct values.

  • Calling student.getAvg() outputs the average marks with the student's name.

  • console.log(this) inside the getAvg function shows that this refers to the student object.

//wrong attempts
// getAvg() {
//     let avg = (eng + math + phy) / 3;  // Causes ReferenceError: eng is not defined
//     console.log(`${this.name} got avg marks = ${avg}`);
// }

Function Context

function getAvg() {
    let avg = (this.eng + this.math + this.phy) / 3;
    console.log(`Avg = ${avg}`)
}

// getAvg();
  • When getAvg() is defined outside the student object and called directly, this refers to the global Window object.

    • In this context, this does not refer to the student object, but instead refers to the global Window object.

    • This happens because the function getAvg is not being called as a method of the student object.

    • Therefore, when the code tries to access this.eng, this.math, and this.phy, it's actually trying to access window.eng, window.math, and window.phy.

    • These properties are not defined on the Window object, so the values will be undefined.

    • As a result, the average avg will be calculated as NaN (Not-a-Number) because any arithmetic operation with undefined results in NaN.
      Call getAvg() in this context will attempt to access properties of the Window object, which will likely result in errors or unexpected behavior.
      alert() is a method of the Window object.