Javascript 从工厂内部调用函数
所以我有一个带一些函数的角度工厂。 我想做的是使用myService获取数据,成功后调用另一个属于工厂的函数:Javascript 从工厂内部调用函数,javascript,angularjs,Javascript,Angularjs,所以我有一个带一些函数的角度工厂。 我想做的是使用myService获取数据,成功后调用另一个属于工厂的函数: myApp.factory('myFactory', function($http) { return { myFunction: function() { MyService.getData().then( function(response) { var so
myApp.factory('myFactory', function($http) {
return {
myFunction: function() {
MyService.getData().then(
function(response) {
var something = response;
this.anotherFunction(something); //returns undefined
},
function (error) {
//something terrible happened
}
);
},
anotherFunction: function(something) {
console.log(something) //will not run
}
}
});
它失败是因为
this。另一个函数
返回未定义的这是一个范围问题-此
未引用您使用它的地方的函数。尝试:
myApp.factory('myFactory', function($http) {
var factory ={}
factory.anotherFunction = function(something) {
console.log(something) //will not run
}
factory.myFunction = function() {
MyService.getData().then(
function(response) {
var something = response;
factory.anotherFunction(something);
},
function (error) {
//something terrible happened
}
);
}
return factory;
});
现在,我们将
工厂初始化为一个对象,将函数分配给它,然后返回它。这意味着您应该能够从第一个函数内部引用factory.anotherFunction()
。虽然我已经订购了,因为我不完全确定吊装是否适用于这种方法,但我可能错了。你必须这样写
myApp.factory('myFactory', function($http) {
var self{};
self.anotherFunction = function(something) {
console.log(something) //will not run
} ;
self.myFunction = function() {
MyService.getData().then(
function(response) {
var something = response;
self.anotherFunction(something); //returns undefined
},
function (error) {
//something terrible happened
}
};
return self;
});
除了@millerbr提供的解决方案,它工作得非常好,我发现使用var=this;变量也解决了这个问题:
myApp.factory('myFactory', function($http) {
return {
var that = this;
myFunction: function() {
MyService.getData().then(
function(response) {
var something = response;
that.anotherFunction(something); //returns undefined
},
function (error) {
//something terrible happened
}
);
},
anotherFunction: function(something) {
console.log(something) //will not run
}
}
})) 仍然一样,如果我不使用thisyes调用它,它返回undefined,它现在可以工作了,而且我发现如果我像那样设置一个变量,var that=this;然后像那样调用函数;同样有效!我应该把它作为第二个答案吗?是的,发出去-这也是另一个很好的解决方案,我完全忘记了!所以,正是我发布的内容,但变量的名称不同?o_o,可能是您键入的速度更快:)…这是一种工厂式的书写方式…不是突破性的政府机密:p chill dude。据我所知,这就像是缓存这个变量;然后使用它的缓存版本,尽管它已经被改变了!但它不是缓存版本。您正在存储对工厂本身的引用,以便以后仍然可以引用它并使用它拥有的函数(或变量)。