function show() { return this.value; } const value = 10; console.log(show());
In a regular function call, 'this' refers to the global object (window in browsers). Since 'value' is declared with const and not attached to the global object, this.value is undefined.
const obj = { value: 42, arrowFunc: () => this.value }; console.log(obj.arrowFunc());
Arrow functions do not have their own 'this'. They use 'this' from the surrounding scope, which here is the global scope. Since value is not defined on the global object, this.value is undefined.
const obj1 = { value: 5 }; const obj2 = { value: 10 }; function getValue() { return this.value; } console.log(getValue.call(obj2));
The call() method calls the function with this set to the first argument. Here, this is obj2, so this.value is 10.
const obj = { value: 100, outer: function() { function inner() { return this.value; } return inner(); } }; console.log(obj.outer());
The inner function is a regular function call, so this inside it refers to the global object, not obj. Since value is not defined globally, it returns undefined.
const button = document.createElement('button'); button.textContent = 'Click me'; const obj = { value: 50, handleClick: () => { console.log(this.value); } }; button.addEventListener('click', obj.handleClick); document.body.appendChild(button);
The arrow function handleClick does not have its own this. It uses this from the surrounding scope, which is the global scope here. Since value is not defined globally, it logs undefined.