在浏览器js代码中寻求将函数作为参数实践传递的建议

时间:2017-12-12 03:21:15

标签: javascript ecmascript-6

我真的只是想知道这是否是“正确”的做事方式,或者我是否缺少关于模块的东西;我们不使用节点,只使用浏览器,但也许这适用于两者。在page.js中我们有一个函数world(),我们需要一个模块(module.js)才能调用。导出world()并将其导入模块似乎不适合做事。

为什么不呢? page.js是js,只适用于一个html页面(page.html); world()操作page.html上的某些特定UI元素,并且不会在其他任何地方重复使用。 Module.js做了一些与ajax / server相关的工作;这是在很多其他html页面上完成的,所以当然我们将它作为一个易于重用的模块。

init()是真正的切入点。举例:

page.js

import mod from 'module.js'

function init() {
    hello(); // print 'hello' to console

    const options = {
        // pass the 'world' function to module.js
        functionParam: world, 

        // some other irrelevant options here
    };

    mod.print(options); // print 'world' to console
}

function hello() {
    console.log('hello');
}

function world() {
    console.log('world');
}

module.js

function print(options) {
    // should call the world function, we should see 'world' logged to console
    options.functionParam();
}

export default print;

0 个答案:

没有答案
相关问题