I can argue that the 'this' keyword is the most confusing part of Javascript for anyone coming from languages ββlike C #.
I read a lot about this on the Internet and on StackOverflow. for example here and here .
I know that the keyword 'this' will be context bound. and in the constructor function, it will be bound to the created object, and when there is no immediate context, it will be bound to the global object (for example, to the window)
I know all this, but the confusion is still not completely cleared; So the best way to understand is to check the codes.
So, I decided to write a little code, and I was surprised at how confused the this keyword is.
here is the code i tested:
function sayHi(name){ var tt = name; return { ss: tt, work: function(anotherName){ alert ("hiiiii " + anotherName); } }; }
as expected, a warning window will appear (Hiiiiii May), then (Wallace). Notice the line sayHi("John"); has no effect.
and now the confusion will start when I replace 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 he warned mthod (Hiiiiiii May) and then (John) not (wallace);
therefore, I had the idea to comment on the sayHi("John"); line sayHi("John"); , but this led to the fact that all the code was not functional and did not work.
demo
I know this might be a newbee question. But it really is confusing here, and I tried to read a lot of articles and questions, but I missed this point.
Why sayHi("John"); string sayHi("John"); sets hi2.ss to John? and why it violates the code when it is deleted; although we call the sayHi method using the new afterward ??