What will the code below output to the console and why? -> Know = Like | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What will the code below output to the console and why? -> Know = Like

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();

14th Aug 2016, 8:16 PM
Thomas Delvoye
Thomas Delvoye - avatar
1 Answer
0
it will output: outer func: this.foo=bar outer func: this.self=bar inner func:this.foo=undefined inner func:self.foo=bar -------- I think it's not a problem to understand what happens in "outer" part, but it can be hard to get t "inner" one. in the inner function "this" is "window", so this.foo is undefined, like window.foo but, "self" keeps the reference to the "myObject", so you can get it's "foo", like "myObject.foo"
12th Sep 2016, 3:01 PM
Илья Маклецов
Илья Маклецов - avatar