我正在开发Angular服务。我在哪里得到错误" TypeError:this.testTwoFunction不是一个函数" for function" testTwoFunction"
angular.module('MobileAppModule')
.run([‘MyService’, function(MyService)
{
console.log("MyService in run");
MyService.init();
}])
.service('MyService', ['$rootScope', function($rootScope)
{
this.init = function() {
testOneFunction();
}
function testOneFunction() {
this. testTwoFunction()
}
this.testTwoFunction = function() {
}
}]);
如何调用函数' testTwoFunction()'
答案 0 :(得分:0)
这与"吊装"有关。 TLDR:testOneFunction是一个函数声明,而testTwoFunction是一个函数表达式(或一个分配给变量的匿名函数" this.testTwoFunction")。在给定的情况下,您需要做一些重新排序:
this.init = function() {
testOneFunction();
};
this.testTwoFunction = function() {
// doing something here
};
function testOneFunction() {
this.testTwoFunction();
}
您可以在此处阅读有关范围界定和提升的更多信息:http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
答案 1 :(得分:0)
尝试使用此代码
(function ()
{'use strict';
angular.module('MobileAppModule',[])
.run(['MyService', function(MyService)
{
console.log("MyService in run");
MyService.init()}])
.service('MyService', ['$rootScope', function($rootScope)
{
var self = this;
self.init = function() {
testOneFunction();
}
self.testTwoFunction = function() {
console.log("severice 2")
}
function testOneFunction() {
self.testTwoFunction();
}
}]);
})();