Javascript: constructor function this keyword

155 views Asked by At

What is the difference between the following two code segments:

function HelloService(){
  var service = this;
  service.itemList = []

  service.hello = function(){    
    return "Hello World!!";
  };

  service.addItem = function(){
    service.itemList.push(1);
  }
}

function HelloService(){
  var service = this;
  var itemList = [];

  var hello = function(){    
    return "Hello World!!";
  };

  service.addItem = function(){
    itemList.push(1);
  }

}

Because as far as I understand the this inside the hello function and outside the hello function points to the same instance.

Could someone explain the above problem w.r.t to JAVA?

EDIT: I have added an addItem function. Here I don't understand the difference between service.itemList and var itemList inside the addItem function. Could you explain the difference inside that function?

1

There are 1 answers

6
Paul On

Local variables in Javascript functions do not get added as properties of this. The first is equivalent to:

function HelloService(){
  this.hello = function(){    
    return "Hello World!!";
  };
}

But not:

function HelloService(){
  var hello = function(){    
    return "Hello World!!";
  };
}

Which does nothing since the function referenced by hello is never used and is not accessible outside the scope of HelloService.