工厂方法内部的功能可以通信

Pro*_*ver 11 angularjs

我对角度js的工厂目录有一个疑问.

假设这是fact1目录.我想在funct2方法中调用funct1方法.

app.factory("fact1",function(){
  return{
     funct1:function(){
        //some code here
     },funct2:function(){
      //some code here
      // call here funct1()
     }
   }
 }); 
Run Code Online (Sandbox Code Playgroud)

先告诉我这是可能的吗?如果可能的话我怎么能在funct2方法中调用funct1方法.

gon*_*ish 13

为什么不这样做:

app.factory("fact1",function(){

    function funct1 () {
        // Do some code...
    }

    function funct2 () {
        // Do some code...
        funct1();
    }

    return{
        funct1: funct1,
        funct2: funct2
    };
}); 
Run Code Online (Sandbox Code Playgroud)

我个人发现这种方式比存储返回对象中的每个函数更有用/可读.此外,我不是this在我的返回对象中使用的忠实粉丝.


dfs*_*fsq 11

当然有可能.这只是普通的javascript对象用法:

return {
    funct1: function () {
        //some code here
    },
    funct2: function () {
        //some code here
        this.funct1();
    }
}
Run Code Online (Sandbox Code Playgroud)

UPD.评论中有一点混乱,认为它不起作用.确实如此,你需要明白如何 funct2调用方法非常重要.也就是说,方法不应该与它的基础对象分离,否则this上下文将是不同的并且this.funct1()将指向错误的(通常不存在的)方法.松散上下文的常见方法:

$('.something').on('click', obj.funct2);
Run Code Online (Sandbox Code Playgroud)

在上面,obj.funct2 this将是HTML元素对象,而obj不再是.但是,以下版本将正常工作:

// use anonymous function
$('.something').on('click', function() { obj.funct2() });

// bind explicitly to context
$('.something').on('click', obj.funct2.bind(obj));
Run Code Online (Sandbox Code Playgroud)

了解MDN文章非常重要:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this