0
我写了一个简单的Angular JS代码,它根据一天的时间向用户致意。它工作正常。下面的代码给出:Angular JS object scope
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);
如果你看到showGreetingMessage
功能它只有一行代码是:
return greeting + ", It's "+ this.showDate();
然而showDate
功能驻留在同一水平作为showGreetingMessage
功能。这就是为什么this.showDate
不应该工作,它应该给错误。但它工作得很好。这是怎么回事?