Angularjs 工厂内部的功能方法可以通信
我对angular js的工厂目录有一个疑问 假设这是fact1目录,我想在funct2方法中调用funct1方法Angularjs 工厂内部的功能方法可以通信,angularjs,Angularjs,我对angular js的工厂目录有一个疑问 假设这是fact1目录,我想在funct2方法中调用funct1方法 app.factory("fact1",function(){ return{ funct1:function(){ //some code here },funct2:function(){ //some code here // call here funct1() } } }); 首先告诉我
app.factory("fact1",function(){
return{
funct1:function(){
//some code here
},funct2:function(){
//some code here
// call here funct1()
}
}
});
首先告诉我这是可能的还是不可能的?
如果可能,那么我如何在funct2方法中调用funct1方法。确保这是可能的。这只是普通的javascript对象用法:
app.factory("fact1",function(){
return{
funct1:function(){
//some code here
},funct2:function(){
//some code here
// call here funct1()
}
}
});
return {
funct1: function () {
//some code here
},
funct2: function () {
//some code here
this.funct1();
}
}
UPD。评论中有点混乱,认为它不起作用。确实如此,但是您需要了解如何调用
funct2
方法非常重要。也就是说,方法不应该从它的基本对象分离,否则这个上下文将不同,这个.funct1()
将指向错误的(通常不存在)方法。释放上下文的常见方法:
$('.something').on('click', obj.funct2);
在上面,obj.funct2
这个
将是HTML元素对象,不再是obj
。但是,以下版本将正常工作:
// use anonymous function
$('.something').on('click', function() { obj.funct2() });
// bind explicitly to context
$('.something').on('click', obj.funct2.bind(obj));
了解MDN文章非常重要:为什么不这样做:
app.factory("fact1",function(){
function funct1 () {
// Do some code...
}
function funct2 () {
// Do some code...
funct1();
}
return{
funct1: funct1,
funct2: funct2
};
});
app.factory("fact1",function(){
var obj = {};
obj.funct1 = function(){
//some code here
}
obj.funct2 = function(){
//some code here
// call here funct1()
obj.funct1();/* calling the funct1 */
}
return obj;
});
我个人发现,这种方法比将每个函数都存储在返回对象中更具可用性/可读性。另外,我不太喜欢在我的返回对象中使用这个。您可以这样做,而不是直接在工厂返回:
app.factory("fact1",function(){
function funct1 () {
// Do some code...
}
function funct2 () {
// Do some code...
funct1();
}
return{
funct1: funct1,
funct2: funct2
};
});
app.factory("fact1",function(){
var obj = {};
obj.funct1 = function(){
//some code here
}
obj.funct2 = function(){
//some code here
// call here funct1()
obj.funct1();/* calling the funct1 */
}
return obj;
});
这应该对你有用。是的不起作用-不确定为什么这是正确的答案。对你有用吗@Mayur@David代码是正确的。然而,你可能用错了。请给我一段您如何在您的案例中调用func2
,我会告诉您为什么它不起作用。更具可读性,避免了this
关键字带来的所有麻烦。我不明白他们在“this”上插入“b”是什么意思?