Why function inside a method refers to the window ??

var obj = {
 show() {
console.log(this);
 function q() {
console.log(this);
}
q()
}
}
June 5th 19 at 21:19
1 answer
June 5th 19 at 21:21
Solution
Due to the fact that you called without a point ? But if, say, you call a normal function in the global object, why do I get the object window ? We function globally declared and called without the "." . - Lavonne25 commented on June 5th 19 at 21:24
Because You have not specified the context.
By default, if you declare a function this = window, it is left of the old js for
sovmestimosti.
New features added to the language, but old - never changed to not" break "existing HTML / JS pages using them.

In a new or strict mode is corrected
var obj = {
 show () {
 console.log (this);
 function q () {
 "use strict";
 console.log (this); // undefined instead of window
};
q();
}
}

Context you can specify here
var obj = {
 show () {
 console.log (this);
 function q () {
 console.log (this);
};
 q.call (this)
}
}

Thanks ес6 or so
var obj = {
 show () {
 console.log (this);
 const q = () => {
 console.log (this);
};
q()
}
}

Read: use strict, this 1, 2
This is a fairly heavy topic, so read, practice, cry, and in a new way. To understand its hard to explain even harder) - jackeline.OConner commented on June 5th 19 at 21:27
Thanks for the links, but I've all read in origanle. The same textbook Cantor, but anglese, there is ES6+. Go hard on these themes) - Lavonne25 commented on June 5th 19 at 21:30

Find more questions by tags JavaScript