首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从数组调用方法和闭包

从数组调用方法和闭包
EN

Stack Overflow用户
提问于 2016-04-13 23:18:51
回答 2查看 47关注 0票数 0

在JavaScript中,您可以这样做:

代码语言:javascript
复制
var Module = (function () {
    var functions = [method1, method2]; // array of functions to execute

    function method1 () {
        console.log('calling method1');
    }

    function method2 () {
        console.log('calling method2');
    }

    function method3 () {
        console.log('calling method3');  // not called
    }

    function add (fn) {
        functions.push(fn); // add new function to the array
    }

    function printt () {
        for (var i in functions) functions[i](); // execute functions in the array
    }

    return {
        add: add,
        printt: printt
    };
})();

Module.add(function () {
    console.log('calling anonymous function');  
});

Module.printt();

// calling method1
// calling method2
// calling anonymous function

(1)要执行的方法存储在数组(2)中,并且可以将新的函数/方法添加到数组中,以便在运行printt方法时执行数组中的所有函数,是否可以这样做?

代码语言:javascript
复制
class Module {
    protected $functions = [];

    public function __construct () {
        // ?
    }

    protected function method1 () {
        echo 'calling method1';
    }

    protected function method2 () {
        echo 'calling method2';
    }

    protected function method3 () {
        echo 'calling method3';
    }

    public function add ($fn) {
        $this->functions[] = $fn;
    }

    public function printt () {
        foreach ($this->functions as $fn)  $fn();
    }
}

$module = new Module();

$module->add(function () {
    echo 'calling anonymous function';
});

$module->printt();
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-04-13 23:29:20

检查可赎回()中的闭包,检查存在()中对象的方法。

代码语言:javascript
复制
class Module {
    protected $functions = ['method1', 'method2'];

    // ...

    public function printt () {
        foreach ($this->functions as $fn) {
            if ( is_callable( $fn ) ) {
                $fn();
            } elseif ( method_exists( $this, $fn ) ) {
                $this->$fn();
            }
        }
    }
}

与JS有一个不同之处,您需要在对象中通过$this正确引用该方法。

票数 2
EN

Stack Overflow用户

发布于 2016-04-14 00:33:11

另一种方法是将成员方法以可调用的形式添加到函数数组中,而不仅仅是方法名称,然后使用call_user_func执行它们。

代码语言:javascript
复制
class Module {
  public function __construct() {
    $this->functions = [
      [$this, 'method1'],
      [$this, 'method2'],
    ];
  }

  // ...

  public function printt() {
    foreach($this->functions as $fn) {
      call_user_func($fn);
    }
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36611197

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档