I´m trying to sort out how 'new' keyword is working in Javascript. But it is has a strange behaviour.
When I run this code in node:
var testing = function() {
self = this;
this.abc = 'abc';
console.log(this); // ====> 1
var subMethod = function () {
console.log(this); // =====> 2
console.log(self === this); // ====> 3
};
//subMethod.apply(this);
subMethod();
};
test = new testing();
// test = testing(); // ===> *4
The console.log(self === this) gives me false.
'this' in nr 1 is { abc: 'abc' }, and 'this' in the sub method is the global 'this' object. Can anyone give me an explanation for this behaviour?
If I run with subMethod.apply(this) then console.log(self === this) is true ({ abc: 'abc' })
When I run without the new keyword (*4) the 'this' variable is the same as the global 'this' (as expected), and also the console.log(self === this) is true.
Why is 'this' in the submethod the same as the global 'this' when running with the 'new' keyword.