Middle
Tell about the context of functions in JavaScript.
sobes.tech AI
Answer from AI
The execution context (this) in JavaScript determines how a function is called and what values are accessible inside it. The context dynamically changes depending on the call method:
- Global context: Outside functions,
thisrefers to the global object (windowin browsers,globalin Node.js).// In a browser console.log(this === window); // true // In Node.js console.log(this === global); // true - Function context:
- Standard call: In non-strict mode,
thisinside a function refers to the global object (if the function is not a method of an object). In strict mode ("use strict";),thiswill beundefined.function showThis() { console.log(this); } showThis(); // Non-strict: Global object; Strict: undefined - Called as an object method:
thisrefers to the object that the method is a part of.const user = { name: 'Alice', greet: function() { console.log("Hello, my name is " + this.name); } }; user.greet(); // Hello, my name is Alice - Called with
new(constructor): Creates a new object, which becomes the value ofthisinside the constructor function, and returns that object.function Person(name) { this.name = name; } const person1 = new Person('Bob'); console.log(person1.name); // Bob - Explicit context specification (
call,apply,bind):call(thisArg, arg1, arg2, ...): Calls the function with the specifiedthisand arguments listed separately.apply(thisArg, [argsArray]): Calls the function with the specifiedthisand arguments as an array.bind(thisArg, arg1, arg2, ...): Returns a new function withthispermanently bound tothisArgand bound arguments.
function introduce(greeting, punctuation) { console.log(greeting + ", I am " + this.name + punctuation); } const person = { name: 'Charlie' }; introduce.call(person, "Hi", "!"); // Hi, I am Charlie! introduce.apply(person, ["Hello", "."]); // Hello, I am Charlie. const boundIntroduce = introduce.bind(person, "Hey"); boundIntroduce("?"); // Hey, I am Charlie?
- Standard call: In non-strict mode,
- Arrow functions: Do not have their own
thiscontext. They capturethisfrom the surrounding lexical scope (the scope in which they were defined).const obj = { name: 'David', sayLater: function() { // `this` here refers to obj setTimeout(() => { // `this` here also refers to obj (inherited from sayLater) console.log("Later, I am " + this.name); }, 1000); } }; obj.sayLater(); // Later, I am David