Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript/Nodejs在外部文件中移动了许多修改内部状态的函数_Javascript - Fatal编程技术网

Javascript/Nodejs在外部文件中移动了许多修改内部状态的函数

Javascript/Nodejs在外部文件中移动了许多修改内部状态的函数,javascript,Javascript,我有一个JavaScript对象,它有很多o函数,可以修改内部状态,我想将所有这些函数移动到一个外部文件中。有一个最好的实践来做到这一点吗? 主要对象是飞机,当飞机飞行时,会发生很多情况。对于每种情况,我都有一个功能,可以改变飞机的内部状态(例如改变发动机的当前速度)。这些函数被命名为situation1,situation2。。。情况。 我想把所有这些函数放在一个类库中。这是否正确和/或可能? 这是一个示例代码 function Engine(){ this.state = 'off'

我有一个JavaScript对象,它有很多o函数,可以修改内部状态,我想将所有这些函数移动到一个外部文件中。有一个最好的实践来做到这一点吗? 主要对象是飞机,当飞机飞行时,会发生很多情况。对于每种情况,我都有一个功能,可以改变飞机的内部状态(例如改变发动机的当前速度)。这些函数被命名为situation1,situation2。。。情况。 我想把所有这些函数放在一个类库中。这是否正确和/或可能? 这是一个示例代码

function Engine(){
    this.state = 'off';
    this.currentSpeed = 0;
}

function Airplane(){
    this.engine1 = new Engine();
    this.engine2 = new Engine();
}

Airplane.prototype.fly = function(){
    //this is for example
    var randomnumber=Math.floor(Math.random()*101);
    switch (randomnumber) {
        case 1: this.situation1();break;
        case 2: this.situation2();break;
        // ...
        case 100: this.situation100();break;            
    }
    this.fly();
}

Airplane.prototype.situation1 = function() { /*change internal state of an Engine* a.e: */ this.engine1.currentSpeed = '200'; }
Airplane.prototype.situation2 = function() { /*change internal state of Engine* a.e: */ this.engine1.currentSpeed = 200 * 3.14; }
// ...
Airplane.prototype.situation100 = function()  { /*change internal state of Engine*/ this.engine2.state = 'on';}


airplane = new Airplane();
airplane.fly();

我相信您正在寻找的是node.js所指的“模块”,如中所述

一种方法是创建一个名为“planer.js”的新文件,其中包含:

// define your main object
var Airplane = function(){
    // initialize it here
};

Airplane.funcOne=function(){ // "class" level function
};

Airplane.prototype.funcTwo=function(){ // "instance" level function
};

// assign Airplane to module exports 
module.exports=Airplane;

// which allows you to:
//     var Airplane=require('Airplane');
如果您不希望在其他代码中使用引擎,可以在Airplane.js中定义它

如果您希望需要从其他代码“require”它,那么您应该将它放入它自己的文件中,并在Airplane.js中“require”它,如:

// Engine.js
var Engine=function(){
};

module.exports=Engine;

// Airplane.js
var Engine=require('Engine');

var Airplane=function(){
};

module.exports=Airplane;
最后,如果要从同一文件中公开飞机和发动机,可以:

var Engine=function(){
};

var Airplane=function(){
};

module.exports={
    Engine:   Engine,
    Airplane: Airplane
};
因此,当您需要另一个文件中的飞机时,您会说:

var Airplane = require('Airplane').Airplane,
    Engine   = require('Airplane').Engine;
更新 作为记录,我不赞成在定义对象的文件之外定义对象的原型方法,但我已经说过

将另一个文件中定义的方法添加到现有对象需要“需要”附加文件,迭代其函数,然后将它们添加到现有对象

最简单的方法是将您的方法定义为:

// file: AirplaneMethods.js

module.exports={

    // what occurs in situation1
    situation1: function(){

        // as expected, 'this' within this method refers 
        // to the object into which this method is "imported."

        return this; // to facilitate method chaining
    },

    // what occurs in situation2
    situation2: function(){
        // ...
        return this; 
    }

    // etc.
};
然后,要将这些方法添加到飞机对象,您需要:

var Airplane=function(){
    // initialization
};

var importedMethods=require('AirplaneMethods');

for(var methodName in importedMethods) {
    Airplane.prototype[methodName]=importedMethods[methodName];
}
或者,对于更一般的解决方案:

/* Import.js -- 20130712 raisch
 *
 * imports methods defined in one or more external paths into an
 * existing object's prototype
 *
 * Usage:
 *
 *     var Import=require('Import');
 *
 *     var Thing=function() {};
 *
 *     Import.from(path1,path2,...).into(Thing);
 *
 *     -or-
 *
 *     Import.into(Thing).from(path1,path2,...)
 *
 */

var util=require('util'),
    assert=require('assert');

var Import=module.exports=function(){};

Import._target=null;

Import._libs={};

// shortcut
var hasOwnProperty=Object.prototype.hasOwnProperty;

// helper
function isEmpty(obj){
    var result=true;
    if(obj===null || 0===obj.length) {
        result=true;
    }
    else if(obj.length && obj.length>0) {
        result=false;
    }
    else {
        for(var k in obj) {
            if(hasOwnProperty.call(obj,k)) {
                result=false;
                break;
            }
        }
    }
    return result;
}

/**
 * requires one or more libs, caching them into self._libs
 *
 * if self._target is not null, calls self.into() to add all lib
 * methods to self._target.prototype
 *
 * @param paths {Array<String>}
 * @returns {Object} self
 */
Import.from=function from(/*path,...*/){
    var paths=Array.prototype.slice(arguments);
    for(var i=0, len=paths.length; i<len; i++){
        var path=paths[i],
            lib=null;
        try{
            lib=require(path);
            if(isEmpty(lib)){
                throw 'requiring "'+path+'" did not produce a useful object';
            }
        }
        catch(e){
            console.error('Import.from failed to require path "%s":%s', path, e);
            continue;
        }
        this._libs[path]=lib;
    }
    this._target && this.into(this._target);
    return this;
};

/**
 * sets target object (class) into which to import lib methods
 *
 * if self._libs is not empty, adds all lib methods to self._target.prototype
 *
 * @param target {Object} into which to import
 * @returns {Object} self
 */
Import.into=function into(target){
    assert.ok(target.prototype, 'Import.into: target must have a prototype');
    this._target=target;
    if(!isEmpty(this._libs)){
        for(var libname in this._libs){
            var lib=this._libs[libname];
            for(var name in lib){
                this._target.prototype[name]=lib[name];
            }
        }
    }
    return this;
};

/**
 * clears library cache
 * @returns {Object} self
 */
Import.clear=function clear(){
    this._libs={};
    return this;
};

/**
 * clears library cache and target object
 * @returns {Object}
 */
Import.reset=function reset(){
    delete this._target;
    this.clear();
    return this;
};
/*Import.js--20130712 raisch
*
*将在一个或多个外部路径中定义的方法导入到
*现有对象的原型
*
*用法:
*
*var Import=require('Import');
*
*var Thing=function(){};
*
*将.from(路径1,路径2,…)导入(对象);
*
*-或-
*
*导入到(事物).from(路径1,路径2,…)
*
*/
var util=require('util'),
assert=require('assert');
var Import=module.exports=function(){};
导入。_target=null;
导入。_libs={};
//捷径
var hasOwnProperty=Object.prototype.hasOwnProperty;
//助手
函数isEmpty(obj){
var结果=真;
if(obj==null | | 0==obj.length){
结果=真;
}
否则如果(对象长度和对象长度>0){
结果=假;
}
否则{
用于(obj中的var k){
if(hasOwnProperty.call(obj,k)){
结果=假;
打破
}
}
}
返回结果;
}
/**
*需要一个或多个LIB,将它们缓存到self中。_libs
*
*如果self.\u target不为null,则调用self.into()以添加所有库
*自我的方法。_target.prototype
*
*@param路径{Array}
*@返回{Object}self
*/
Import.from=函数from(/*路径,*/){
var path=Array.prototype.slice(参数);

对于(var i=0,len=path.length;我需要回复,但可能我没有很好地解释问题所在。我想将所有的platform.prototype.situationX函数放在一个外部文件中,做一种库,在fly函数中调用时可以更改飞机状态。你可以通过将飞机对象的定义放入它自己的文件。您是否只想将所有的Airport.prototype函数放入它们自己的文件中?如果是,我将编辑我的答案以表明这也可以。是的,我想将所有Airport.prototype函数放入它们自己的文件中,因为它们是100个函数。