我有一些工厂:
app.factory('myFactory', function() {
return {
property1: "str",
property2: "str",
property3: "str",
func: function() {/*....*/},
childObj:{
prop1: "str",
prop2: "str",
childFunc: function() {
//....;
func();
}
}
}
})
我可以在子方法中调用父工厂方法吗?
最佳答案
But can I call parent method inside child method inside Angularjs factory?
正如您定义的工厂 - 否
app.factory('myFactory', function(){
return{
property1:"str",
property2:"str",
property3:"str",
func:function(){
return "fess";
},
childObj:{
prop1:"str",
prop2:"str",
childFunc:function(){
return func(); // here you will get error: func() is undefined
}
}
}
})
<小时/>
但是,当我们创建 factory
var 时,这将起作用:
app.factory('myFactory', function(){
var factory = {
property1:"str",
property2:"str",
property3:"str",
func:function(){
return "fess";
},
childObj:{
prop1:"str",
prop2:"str",
childFunc:function(){
return factory.func(); // <-- OK
}
}
};
return factory;
})
调用:
console.log(myFactory.childObj.childFunc()); // fess
关于javascript - 调用父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46049585/