2016-12-20 13 views
1

JavaScriptを使い慣れていない(いくつかの基本的なチュートリアルを通して)誰かが私がここで間違っていることを教えてもらえますか?私はrun関数を参照しようとしているので、withinCircle関数を参照し、次にそのすべてを別のファイルにエクスポートしようとしています。とにかく私のコードを変更してもよろしいですか?私は「ベスト」プラクティスに従おうとしましたが、私はうんざりしているかもしれません。ありがとう!別のクラスにインポートされたモジュール内の関数を呼び出す

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'); 
+0

runとwithinCircleは同じオブジェクトの一部です。私はあなたがする必要があるのは、 'this'を使って関数を呼び出すことだと思います。' var pp = this.withinCircle(...); ' –

答えて

0

を:

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

module.exports = add 

および他のファイルに:

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

console.log(add(1,1)) 

それらのパスは、ファイルの場所に対するものです。拡張子を省略することができます。

エクスポート/正常に動作させるには、nodeまたはbrowserifyまたはwebpackが必要です。

modular javacriptの詳細については、look thereを参照してください。ブラウザワールドに入力しなくても、私たちが今日できることをあなたに提示します。

EDIT:あなたは次の操作を行うことができ、よりシンボルをエクスポートするために

消費者で
// 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 
/ES6モジュールは、あなたが thereを確認することができます異なるidionを、持って使用している場合

// bar3.js 
const add  = require("./foo3").add 
const multiply = require("./foo3").multiply 
//... 

消費者には、関連する変更を必要としません。

+0

こんにちは、情報、@ Rilcon42、それが今役立つことを願って – Sombriks

関連する問題