工厂方法内部功能可以沟通 [英] Function inside factory method can communicate

查看:110
本文介绍了工厂方法内部功能可以沟通的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于JS角的工厂目录中的一个疑问。

i have one doubt regarding the factory directory of angular js.

想这是fact1目录。我想打电话给funct1的funct2方法中的方法。

suppose this is fact1 directory .I want to call funct1 method inside the funct2 method.

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

先告诉我这是可能或不?
如果可能的话,我怎么可以叫funct1的funct2方法中的方法。

first tell me this is possible or not? if possible then how i can call funct1 method inside the funct2 method.

推荐答案

当然这是可能的。这只是正常的JavaScript对象用法:

Sure it's possible. This is just normal javascript object usage:

return {
    funct1: function () {
        //some code here
    },
    funct2: function () {
        //some code here
        this.funct1();
    }
}


UPD 。有在其不工作的评论有点混乱。它,但你要明白,这是非常重要的如何 funct2 方法被调用。也就是说,方法不应该被分离从它的基本对象,否则这个上下文将是不同的, this.funct1()将指向错误的(通常是不存在的)方法。松散的背景下常见的方式:


UPD. There was a little confusion in comments that it does not work. It does, however you need to understand that it's very important how funct2 method is called. Namely, method should not be detached from it's base object, otherwise this context will be different and this.funct1() will point to the wrong (usually inexistent) method. Common way to loose context:

$('.something').on('click', obj.funct2);

在上面, obj.funct2 这个将HTML元素的对象,而不是 OBJ 了。不过,下面的版本将正常工作:

In the above, obj.funct2 this will be the HTML element object, not the obj anymore. However, below version will work properly:

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

// bind explicitly to context
$('.something').on('click', obj.funct2.bind(obj));

下面是非常重要的,了解MDN文章: HTTPS ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Here is very important to understand MDN article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

这篇关于工厂方法内部功能可以沟通的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆