2017-09-05 73 views
0

我有一些厂:调用父方法

app.factory('myFactory', function() { 
    return { 
    property1: "str", 
    property2: "str", 
    property3: "str", 
    func: function() {/*....*/}, 
    childObj:{ 
     prop1: "str", 
     prop2: "str", 
     childFunc: function() { 
     //....; 
     func();  
     } 
    } 
    } 
}) 

我能叫孩子方法内部父工厂方法?

回答

1

但是我可以在Angularjs工厂内的子方法里面调用父方法吗?

正如你所定义的工厂 - 没有

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 

Demo Plunker

+0

谢谢U,我会做像你说的) – RoGGeR