Issue
Can anyone answer this?
What will the code below output to the console and why?
(function(){
var a = b = 3;
})();
console.log("a defined? " + (typeof a !== 'undefined'));
console.log("b defined? " + (typeof b !== 'undefined'));
What will the code below output to the console and why?
var myObject = {
foo: "bar",
func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
(function() {
console.log("inner func: this.foo = " + this.foo);
console.log("inner func: self.foo = " + self.foo);
}());
}
};
myObject.func();
Solution
First Code:
(function(){
var a = b = 3;
})();
console.log("a defined? " + (typeof a !== 'undefined'));
console.log("b defined? " + (typeof b !== 'undefined'));
Output:
a defined? false
b defined? true
Explaination:
Here you are using Immediately Invoked function Expression(IIFE). Here a
is declared inside function’s scope but b
is not declared due to which it gets registered to the global scope. Now since you are accessing a
and b
outside in the global scope a
is undefined
but b
is defined
.
Second Code:
var myObject = {
foo: "bar",
func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
(function() {
console.log("inner func: this.foo = " + this.foo);
console.log("inner func: self.foo = " + self.foo);
}());
}
};
myObject.func();
Output:
outer func: this.foo = bar
outer func: self.foo = bar
inner func: this.foo = undefined
inner func: self.foo = bar
Explaination:
The key here is this
reference inside a function which is an object’s property is that object itself. So first two logs
print the expected result. Then you are using an IIFE and this
reference inside IIFE is the global Object(Window object)
. Therefore this.foo
means Window.foo
there which is undefined
. However self
is accessable inside that function which has value equal to that object. Hence it prints the foo
variable.
Answered By – Rohit Agrawal
Answer Checked By – Marilyn (AngularFixing Volunteer)