简体   繁体   English

代码重构。 在类的所有实例上运行的方法

[英]code refactoring. Method that operates on all instances of the class

I have a class constructor whose main work is to instantiate Objects. 我有一个类构造函数,其主要工作是实例化对象。 It takes ID, checks that object with such ID was not created before and creates it. 它获取ID,检查之前没有创建具有该ID的对象,然后创建它。

function Vehicle(ID){
    if (this.listOfVehicles.indexOf(ID) !== -1) throw new Error('Vehicle with such ID already exists');
    this.ID = ID;
    this.listOfVehicles.push(ID);
    this.isMoving = true;
}

Prototype of the object has the storage of all the object IDs and two methods run - which makes the vehicle moving and stopAll, which stops all vehicles. 对象的原型具有所有对象ID的存储和两种运行方法-使车辆移动和stopAll,这将停止所有车辆。

Vehicle.prototype = {
    'listOfVehicles' : [],
    'run'            : function(){
        this.isMoving = true;
    },
    'stopAll'           : function(){
        var vehicleID, i, listOfVehicles = Vehicle.prototype.listOfVehicles;
        for(i = 0; i < listOfVehicles.length; i++){
            vehicleID = listOfVehicles[i];
            vehicles[vehicleID].isMoving = false;
        }
    }
};

Basically everything is working nicely: 基本上一切都运行良好:

var vehicles = {};
vehicles[3] = new Vehicle(3);
vehicles[6] = new Vehicle(6);
vehicles[12] = new Vehicle(12);

All vehicles are instantiated and moving 所有车辆都实例化并移动

vehicles[3].stopAll();

All vehicles are not moving 所有车辆均未行驶

vehicles[3].run();

only vehicle 3 i moving 我行驶的只有车辆3

There is one thing, I do not like here. 有一件事情,我不喜欢这里。 In order to stop all vehicles I need to use method from some of the vehicles. 为了停止所有车辆,我需要使用某些车辆的方法。 But I can not think of any better way of doing it. 但是我想不出更好的方法。

You can define: 您可以定义:

Vehicle.stopAll = function () {
    var vehicleID, i, listOfVehicles = Vehicle.prototype.listOfVehicles;
    for(i = 0; i < listOfVehicles.length; i++){
        vehicleID = listOfVehicles[i];
        vehicles[vehicleID].isMoving = false;
    }
}

There's actually nothing requiring you to attach this function to the class, you could also define it as: 实际上,没有什么要求您将此函数附加到类上,也可以将其定义为:

function stopAllVehicles () {
    var vehicleID, i, listOfVehicles = Vehicle.prototype.listOfVehicles;
    for(i = 0; i < listOfVehicles.length; i++){
        vehicleID = listOfVehicles[i];
        vehicles[vehicleID].isMoving = false;
    }
}

because Javascript classes don't implement information hiding (you can do that yourself by enclosing information in local variables of functions). 因为Javascript类不会实现信息隐藏(您可以自己将信息包含在函数的局部变量中来实现)。

Or you can use your original class definition, and use Vehicle.prototype.stopAll() . 或者,您可以使用原始的类定义,并使用Vehicle.prototype.stopAll() Since JS uses prototype-based OO, there's always a vehicle available to call the method on. 由于JS使用基于原型的OO,因此总有一种方法可以调用该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM