调用导入到另一个类的模块内的函数

时间:2016-12-20 23:53:48

标签: javascript

我是JavaScript新手(通过一些基础教程)。谁能告诉我这里做错了什么?我试图让run函数引用withinCircle函数,然后将整个函数导出到另一个文件,以便我可以引用run函数。无论如何你都可以随意修改我的代码 - 我试着遵循" best"做法,但我可能搞砸了。谢谢!

var roleGuard = {

    /** @param {Creep} creep **/
    run: function(creep) 
    {
        var target = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {filter: { owner: { username: 'Invader' } }});
        if(target!=null)
        {
            console.log(new RoomPosition(target.pos.x,target.pos.y,'sim'));
            //ranged attack here
            //within 3, but further than 1
            if(creep.pos.getRangeTo(target)<=3&&creep.pos.getRangeTo(target)>1) 
            {
                creep.rangedAttack(target);
                console.log("ranged attacking");
            }
        }
        else
        {
            var pp=withinCircle(creep,target,3,'sim');
            console.log(pp);
            creep.moveTo(pp);
        }
    }
//------------------------------------------------------------
//move to closest point within z units of given evenmy
    withinCircle: function(creep,target,z,room)
    {
        var targets = [new RoomPosition(target.pos.x-z,target.pos.y-z,room), new RoomPosition(target.pos.x+z,target.pos.y-z,room),new RoomPosition(target.pos.x-z,target.pos.y+z,room),new RoomPosition(target.pos.x+z,target.pos.y+z,room)];
        var closest = creep.pos.findClosestByRange(targets);
        return(closest);
    }
//------------------------------------------------------------
};
module.exports = roleGuard;

其他文件包含:

var roleGuard = require('role.guard');

1 个答案:

答案 0 :(得分:0)

例如:

sudo /usr/sbin/apachectl restart

并在另一个文件中:

// foo.js
function add(a,b){
  return a + b
}

module.exports = add

这些路径是相对于文件位置的。扩展名可以省略。

您需要nodebrowserifywebpack才能使出口/需要正常运作。

如果您想要更好地解释模块化javascript look there,即使您没有进入browserify世界,它也会向您展示我们现在可以做的事情。

修改

要导出更多符号,您可以执行以下操作:

// bar.js
const add = require("./foo");

console.log(add(1,1))

然后在消费者中:

// foo2.js
function add(a,b){
  return a + b
}

function multiply(a,b){
  return a * b
}

module.exports = {
  add:add,
  multiply:multiply
}

这也是有效的:

// bar2.js
const add      = require("./foo2").add
const multiply = require("./foo2").multiply
//...

消费者无需进行相关更改:

// foo3.js
function add(a,b){
  return a + b
}
exports.add = add

function multiply(a,b){
  return a * b
}
exports.multiply = multiply

如果使用babel / es6模块具有不同的idion,您可以检查there