0

I have the following code-

var x=function(){
  alert("hello");
}
var z=x;
z();// it works nicely

Now say I modified the code a bit-

 var x=function(){
   this.show=function(){
   alert("hello");
   }
 }
 var z=x;// It doesn't work unless I write var z=new x(); 
 z.show();

I am wondering what difference 'this' keyword is creating between this two function and why I need to use an extra new keyword in the second case.

SynozeN Technologies
  • 1,291
  • 1
  • 12
  • 19
APL
  • 353
  • 1
  • 15
  • z.show doesn't work with `z = x` because z.show doesn't exist until the function is called. creating a `new x()` will in effect start the function and store it as z. Inside of x you've told the program that `this.show` will be a function. calling `z.show` without newing it up would be like calling a static function on a class, which i'm pretty sure JS doesn't have – Premier Bromanov May 24 '17 at 15:39
  • You could return an object from `x` function call which has property `"show"` – guest271314 May 24 '17 at 15:41

0 Answers0