I can claim that 'this' keyword is the most confusing part of Javascript for those who comes from languages like C#.
I have read a lot about this on the internet and on StackOverflow too. like here and here.
I know that 'this' keyword will be bound to the context. and in constructor function it will be bound to the object being created, and when there is no immediate context it will bound to global object (i.e window)
I know all that , however confusion is still not fully cleared; So the best way to understand is by testing codes.
So I decided to write small code and I was surprised by how much convoluted the this keyword.
here is the code i tested:
function sayHi(name){ var tt = name; return { ss: tt, work: function(anotherName){ alert ("hiiiii " + anotherName); } }; } //this method invocation has no effect at all right now sayHi("John"); var hi2 = new sayHi("wallace"); hi2.work("May"); alert(hi2.ss); as expected the alert window will show (Hiiiiii May ) then ( wallace). Notice now that the line sayHi("John"); has no effect at all.
and Now the confusion will start when I change one thing ONLY (change var tt => this.tt):
function sayHi(name){ //this is the ONLY change I did. this.tt = name; return { ss: tt, work: function(anotherName){ alert ("hiiiii " + anotherName); } }; } // Now this line invocation will be problematic sayHi("John"); var hi2 = new sayHi("wallace"); hi2.work("May"); alert(hi2.ss); the result surprised me when the alert mthod gave ( Hiiiiiii May ) and then (John) not (wallace);
so I had the idea to comment the line sayHi("John"); but that resulted in the whole code being no-functional and not working.
the demo is here
I know this might be newbee question. But it is really confusing here and I did try to read many articles and SO questions but i m missing this point.
Why does the line sayHi("John"); setting the hi2.ss to John?? and why does it break the code when we delete it ; although we invoke the sayHi method by using the new keyword afterward ??
thisisundefinedwhen a function is invoked without any context.ss: tt,is assigning based on a local var, not a property of this, since the var doesn't exist it should be undefined.