User Tools

Site Tools


java-script:function-context

This is an old revision of the document!


Java Script Function Context

This

this keyword relates to the context on which it is run.
person.sayHello() ⇒ context here is person
person.spouse.sayHello(); ⇒ context is spouse
sayHello() ⇒ context is window for web browsers, globalThis for Node.js >=12 or global for Node.js < 12.

Given this example:

function-context-this.js
function sayHello() {
  console.log(this.name, this.age);
}
 
const person = {
  name: 'Alice',
  age: 30,
  sayHello: sayHello,
  spouse: {
    age: 32,
    sayHello: sayHello
  }
};
 
person.sayHello(); // Alice, 30
person.spouse.sayHello(); // undefined, 32
sayHello(); // undefined, undefined

When you call person.spouse.sayHello(), this.name evaluates to undefined since there's no name property on the spouse object, and this.age evaluates to 32.

In non-strict mode, this refers to the global object, and since there's no name or age property on the global object, both will be undefined.
So sayHello(); in non strict mode will display undefined, undefined. But in strict mode, it will throw an error.

In strict mode, this inside the sayHello function will be undefined when called without an object, leading to a TypeError when attempting to access properties on it:
"use strict";
 
function sayHello() {
  console.log(this.name, this.age);
}
 
// ... rest of the code ...
 
sayHello(); // TypeError: Cannot read properties of undefined (reading 'name')

Call, Apply, Bind

java-script/function-context.1691576066.txt.gz · Last modified: 2023/08/09 13:14 by odefta