javascript - Can someone explain working of this js code with reference to 'this' keyword? -


js code is:

this.sound1 ="global";  function cat(){     this.sound = 'meawo!!!!';     this.sound1 = 'meawooooo!!!!';      meawo1 = function(){         console.log(this.sound1);         console.log(this);     };      function meawo2(){         console.log(this.sound1);         console.log(this);     };      this.meawo = function(){         console.log(this.sound);         console.log(this);         meawo1();         meawo2();     };  };  var c = new cat(); c.meawo(); 

output is: enter image description here

question: how come this inside of meawo1(function expression) & meawo2(function expression declaration) referring "global" , not object c? why that?

always remember simple tip while wanting know object this refer to.

obj.method(); 

in above, method's called on obj, , hence this in method it's called on, i.e obj = this.

in case, though meowo called on c, meowo1 , meowo2 aren't on object want refer to.

functions don't have explicit scope called, default global context, though function isn't global , can leverage variables in parent context due closure.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -