1

This might be a very easy issue. I am still learning javascript and hoping I can get help for the issue below.

var hello = function()
{
    this.hey = function()
    {
        console.log("hey");
    }
    function init()
    {
        this.hey();
    }
    init();
}
var h = new hello();

The above code is complaining the method hey is not defined. But if I do

var h = hello();

It didn't give any issues.

Why is the first one with the new that creates an object gave me error but the second one didn't? I need to create the object, thus I need to use the new keyword. How can I resolve the error I got from first one?

s-hunter
  • 24,172
  • 16
  • 88
  • 130

1 Answers1

1

When you are calling hello method with new, it will create a new instance of hello function/class and you will get a this as a context of hello function.

 var hello = function () {
     // this is an instance of hello class
     this.hey = function () {
         console.log("hey");
     }

     var _this = this; // creating this context of hello
     function init() {
         // this is a context of window here
         //this.hey(); // throws an error
         _this.hey(); // will execute
     }
     init();
 }
 var h = new hello(); // create a new instance/object of hello

While, when you simply calling it as a function hello(), you will get a window context inside hello function.

var hello = function () {
     // this is a context of window here
     this.hey = function () {
         console.log("hey");
     }

     function init() {
         // this is a context of window here
         this.hey(); // will execute
     }
     init();
 }
 var h = hello(); // calling a hello function

JSFIDDLE DEMO: http://jsfiddle.net/8QN7W/

Mohit Pandey
  • 3,679
  • 7
  • 26
  • 38