gliese 581 g
gliese 581 g

Reputation: 379

Angular JS object scope

I have written a simple Angular JS code which greets user depending on the time of the day. It works fine. The code is given below:

var modSvc = angular.module("appName",[]); 

modSvc.provider("date",function(){
    var greeting;
    return {
        showGreeting:function(value){
            greeting = value;
        },
        $get:function(){
            //it has to return an object which can have variables and functions
            return {
                showDate:function(){
                    var date = new Date();
                    return date.getHours();
                },
                showGreetingMessage:function(){                 
                    //var date = new Date();
                    return greeting + ", It's "+ this.showDate();
                }
            }
        }
    };
});

modSvc.config(function(dateProvider){
    var hours = dateProvider.$get().showDate();
    if(hours<12)
        dateProvider.showGreeting("Good morning!");
    else if(hours<17)
        dateProvider.showGreeting("Good afternoon!");
    else if(hours<22)
        dateProvider.showGreeting("Good evening!");
    else
        dateProvider.showGreeting("Good night!");
});

function serviceController($scope,date){
    $scope.greetingMessage = date.showGreetingMessage();
}

modSvc.controller("svcController",serviceController);

If you see showGreetingMessage function it has only one line of code which is:

return greeting + ", It's "+ this.showDate();

However showDate function resides at the same level as that of showGreetingMessage function. That's why this.showDate should not work and it should give error. But it works perfectly fine. How is it so?

Upvotes: 0

Views: 50

Answers (1)

Adwaenyth
Adwaenyth

Reputation: 2110

It depends on the JavaScript engine that is used but according to the Mozilla reference your "this" actually references the parent object since you are returning an object.

As an object method

When a function is called as a method of an object, its this is set to the object the method is called on.

In the following example, when o.f() is invoked, inside the function this is bound to the o object.

var o = {
  prop: 37,
  f: function() {
    return this.prop;
  }
};

console.log(o.f()); // logs 37

Upvotes: 1

Related Questions