Sobes.tech
Junior — Senior

What will the console output when calling object methods in JavaScript

livecode

Task condition

It is necessary to predict what values will appear in the console after executing each line of code below. Pay attention to the differences between regular functions and arrow functions, as well as the influence of bind and the loss of context.

var person = {
    firstName: 'Bill',
    lastName: 'Ivanov',
    sayName: function() {
        console.log(this.firstName);
    },
    sayLastName: () => {
        console.log(this.lastName);
    }
};

person.sayName(); // ?

var unboundSayName = person.sayName;

unboundSayName(); // ?

person.sayName.bind({ firstName: 'Boris' })(); // ?

person.sayName(); // ?
person.sayLastName(); // ?

person.sayName.bind({ firstName: 'Boris' }).bind({ firstName: 'Tom' })(); // ?
person.sayLastName.bind({ lastName: 'Petrov' })(); // ?