Reputation: 505
var abc=(function(){
var self=this;
return {
self:self
}
})();
When doing abc.self
I get undefined
what does this
happen to be in this context.
Upvotes: 4
Views: 74
Reputation: 382344
What you have can be simplified for the purpose of the explanation in
(function(){ console.log(this) })();
Your expression (in the first set of parenthesis) defines a function. You then call this function without context (the this
). This construct is called an IIFE. As you don't pass a context, the behavior depends whether it is called in strict mode or not :
In non strict mode, you would have the global object (window
in a browser, global
in node).
In strict mode, a missing context of a function call isn't replaced, it's undefined
.
As you get undefined
, I guess you're in strict mode. You probably have "use strict";
at the start of the file or in an enclosing function.
If you wanted to pass a context, you might for example have done
(function(){ console.log(this) }).call(someobject);
Upvotes: 4
Reputation: 85573
this
refers to the current object. In your condition this
will be window
, and as you're trying to get the value abc.self
, you need to use like this:
this.self = this;
Now, only you can get the value:
var xyz = new abc();
xyz.self
But to note, you cannot use abc as the constructor like above code because you are using the closure.
Upvotes: 1
Reputation: 17926
in that "root scope" this
is window
and
console.log(abc.self);
results for me in
Window {top: Window, window: Window, ...}
Upvotes: 1