-1

Here, the property "self" is given a value as "this". what will be output of the current scenario

var obj = {
   foo: "bar",
   self: this,
   myfunc: function() {
     console.log("1 " + obj.foo);
     console.log("2 " + self.foo);
     (function() {
        console.log("3 " + obj.foo);
        console.log("4 " + self.foo);
      })();
   }
};

obj.myfunc(); //invoking the object's function
amrender singh
  • 6,982
  • 3
  • 17
  • 25
suDemb
  • 1
  • 1
  • 1
    `what will be output of the current scenario` - don't you know? is that your question? did you try? – Jaromanda X Jun 09 '18 at 07:51
  • I am not getting expected output, i was thinking of getting below mentioned output: bar bar bar bar but getting different,so need some explanation about this. – suDemb Jun 09 '18 at 08:30
  • 1
    `this` points to `Window` which does not have a property `foo`. – str Jun 09 '18 at 08:33

1 Answers1

2

this given as value to self in obj points to context of whoever creating obj. If you run directly it is window object.

this in below case used in myFunc points to context of obj object so you can get value of this.foo as "bar".

// context: window
var obj = {
   foo: "bar",
   self: this,
   myfunc: function() { // context: obj
     console.log("1 " + this.foo);
     console.log("2 " + this.self.foo);
     (function() { // context: window
        console.log("3 " + this.obj.foo);
        console.log("4 " + this.self.foo);
      })();
   }
};

obj.myfunc(); //invoking the object's function
Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
Vivek
  • 1,307
  • 11
  • 24