0

Want to see why printName() function console.log not printing the value? What is the value this holds?

const person = {
    firstname: 'John',
    lastname: 'Muir',
    name: 'hello',
    fullname() {
        const name = 'Tim';
        this.name = 'Tim';
        console.log(JSON.stringify(this));
        console.log('First name ' + this.firstname);
        console.log('Last name  '+ this.lastname);

        printName = function () {
            console.log('name again ' + this.name);
        };

        printName();
    }
}

    person.fullname();

Output

{"firstname":"John","lastname":"Muir","name":"Tim"}
First name John
Last name  Muir
name again undefined
swam1j77
  • 1
  • 1
  • Because printName function is not directly defined in object and (this) keyword returns the current object – Shahghasi Adil Apr 29 '22 at 19:48
  • A tip: add the statement `console.log(printName)` after the `person.fullname()` call. You will see a function object gets printed to the console instead of an error, even though it doesn't appear to be in scope, because it is being attached to the global object. Therefore `this` refers to the global object inside the function itself. – lawrence-witt Apr 29 '22 at 19:57
  • Thanks Shahghasi Additional question, console.log('hello again ' + this === globalThis); should be true ? @lawrence-witt – swam1j77 Apr 29 '22 at 20:26
  • No, because order of operation evaluates arithmetic before equality. `'hello again' + this` equals the string `hello again [object Window]`. But `console.log(this === globalThis)` should print true. – lawrence-witt Apr 29 '22 at 20:33

0 Answers0