DEV Community

Discussion on: Let me explain to you what is `this`. (Javascript)

Collapse
 
elarcis profile image
Elarcis

this in the body of f is undefined!!! not obj!!!

Why does it happen though, that this code ran on Firefox (and I suppose, any other browser):

function f() { console.log(this); }

f();

const obj = {};
obj.fn = f;
obj.fn();
Enter fullscreen mode Exit fullscreen mode

prints respectively the Window object and the obj one?

Collapse
 
ycmjason profile image
YCM Jason • Edited

Great question. You are getting Window because you are not using 'use strict'.

Go to this link and the section called "Securing JavaScript" explains it.

developer.mozilla.org/en-US/docs/W...

Collapse
 
elarcis profile image
Elarcis

Oops. That actually explains a lot, as I used to get could not read property 'foo' of undefined a lot when passing my functions around as references, in strict mode.

Thank you for the link, I had forgot how much use strict mode changes the game!

Thread Thread
 
ycmjason profile image
YCM Jason • Edited

It makes code a little bit more reasonable.

Babel has implicit strict mode and u don't have to worry about forgetting to add it. :)

Collapse
 
gmartigny profile image
Guillaume Martigny

Without specific definition, this is the object wrapping the function. window is the fallback when can't be infer from any context.

Collapse
 
yahyaouimohamed profile image
yahyaoui-mohamed

To get undefined as result you have to use the strict mode.