Sobes.tech
Middle

Live coding: determine the output in the console for code with functions, arrow functions, objects, and context (this), call/bind.

sobes.tech AI

Answer from AI

In JavaScript, the execution context (this) depends on how the function is called. Arrow functions do not have their own this — they inherit it from the outer lexical environment.

Example:

const obj = {
  value: 42,
  regularFunc: function() {
    console.log(this.value);
  },
  arrowFunc: () => {
    console.log(this.value);
  }
};

obj.regularFunc(); // 42 — this refers to obj
obj.arrowFunc();   // undefined or the value from the outer context (e.g., window.value)

// Using call/bind:
function show() {
  console.log(this.name);
}

const user = { name: 'Alice' };

show.call(user); // Alice
const boundShow = show.bind(user);
boundShow(); // Alice

Thus, call and bind allow explicitly setting this when calling a function, but they do not work with arrow functions, as their this is fixed lexically.

Live coding: determine the output in the console for… - sobes.tech