confusion about the 'this' keyword in Javascript
javascript, this
Solution
When you first invoke `sayHi("John");`, `this` will point to the global object `window`. That means `this.tt = name` actually creates a global `tt` variable.
Then when you invoke `new sayHi("wallace");`, `this` correctly points to a new instance of `sayHi`, but you are returning another object instead of letting `new` naturally return the instance.
If you carefully look at your object literal, you define `ss` like `ss: tt,`. Since you aren't using `this.tt` and there is no `tt` symbol found in the constructor's scope, the value will then be resolved as a global variable (which was previously set to `John`).
Problem
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 ??