Skip to content

Context

sjagoori edited this page Jun 20, 2020 · 4 revisions

Context

In programming, the context is nearly always the scope within the code is written in. This means that, for example, this can refer to a variable within a function scope.

Strict mode vs. sloppy mode

Javascript exists in two modes; the sloppy mode (default) and the strict mode. In the strict mode, the compiler would instead of ignoring throw errors. This extends to non-writable global names and property.

* strict mode

'use strict'
undefinedVariable = 20

console.log(undefinedVariable)
// ReferenceError: undefinedVariable is not defined
* sloppy mode
undefinedVariable = 20

console.log(undefinedVariable)
// 20

Global context

The global context is the context that is not inside any function. In this context (if executed in a browser), this refers to the window which contains the properties of that window such as events and other metadata.

this.a = 20 

function something(){
  return this.a
}

console.log(something())
// undefined
console.log(this.a)
// 20

Function context

In the context of a function, it depends on how the function is called. In a scenario where the code is executed in sloppy mode, the value of this would be window whereas in a strict mode it'd be undefined.

function strictMode() {
  'use strict'
  return this
}

function sloppyMode() { 
  return this
}

console.log(typeof strictMode()) 
// undefined
console.log(typeof sloppyMode()) 
// object- where all window properties are

Class context

In the context of classes, this can refer to multiple things. For example, in the constructor, the this refers to the incoming value whereas in getType() this refers to the type() function in the class.

class Pokemon {
  constructor() {
    this.getType.bind(this);
  }

  getType() {
    console.log(`This is a ${this.type} type pokemon`);
  }
  get type() {
    return 'fire';
  }
}

const charmander = new Pokemon();
charmander.getType();
// This is a fire type pokemon

Source

this. (2020, June 2). Retrieved from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this