Sobes.tech
Junior — Senior

Исследование контекста this при разных способах вызова функций

livecode

Task condition

This example demonstrates how the value of this changes in regular functions, object methods, and arrow functions. It shows direct calls as well as the use of call, apply, and bind, including an attempt to re-bind an already bound function.

const methodKey = "fn3";

const container = {
    fn1: function () {
        console.log(this);
        const f = () => console.log(this);
        f();
    },
    fn2() {
        console.log(this);
    },
    [methodKey]: () => console.log(this),
};

console.log(this); //

container.fn1(); //
container.fn2(); //
container[methodKey](); //

const external = {
    new: 123,
};
const boundFn = container.fn1.bind(external);
boundFn.bind(this); //

container.fn2.call(external); //
container[methodKey].apply(external); //