New Javascript keyword in subfunctions
I'm trying to figure out how the "new" keyword works in Javascript. But this is strange behavior.
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
Console .log (self === this) gives me false. The 'this' in nr 1 is {abc: 'abc'}, and the 'this' in the subfield is the global object 'this'. Can anyone give me an explanation for this behavior?
If I run with subMethod.apply (this) then console.log (self === this) is true ({abc: 'abc'})
When I run without a new keyword (* 4) the variable 'this' matches with a global 'this' (as expected) and console.log (self === this) is true.
Why is 'this' in the subtopic the same as the global 'this' when working with the keyword "new".
source to share
When you call new testing()
, the function testing
runs with its context ( this
) as a new object. This object will be the first. Internally, when you run it subMethod()
, it runs in the global context. This is how JS does it. Therefore, this
there is window
and self !== this
. If you call it in context this
( subMethod.apply(this)
), then naturally self === this
.
When you call testing()
, it runs in the global context. When you add abc
, it is global, and this
- window
. When you call subMethod()
it is also called in the default global context and as such self === this
.
So basically, a simple function works in a global context. Running a function as a constructor (c new
) creates a new context. Method run (for example "abaca".split('a')
) is called in the context of the underlying object - split
called with "abaca"
as this
.
Does it help?
source to share