DEV Community

Discussion on: Understanding "this" in JavaScript

Collapse
 
js2me profile image
Sergey S. Volkov • Edited

Thanks for good article!
Can you explain more why this
code returns exception?

let person = {
    firstName: 'George',
 }

 function printName(greeting) {
  console.log(greeting + this.firstName)
 }

 printName('hello') // Uncaught TypeError: Cannot read property 'firstName' of undefined
Enter fullscreen mode Exit fullscreen mode

Just context of the printName function refers to window object, as I understand, and because of this output should be helloundefined ?

Collapse
 
naimlatifi5 profile image
Naim Latifi • Edited

Hello guys

Thanks for pointing this out and you are both right, by default it should output hello undefined but here I run the code in a strict mode which was my mistake I forgot to mention it(now edited and corrected ). So running this in strict mode it will throw an exception and output with TypeError :)

Collapse
 
donnisnoni profile image
Don Alfons Nisnoni • Edited

BTW, it would work


let person = {
  firstName: 'George'
}

person.printName = function(greeting) {
  console.log(greeting + " " + this.firstName)
}


printName('Hello') // Hello George