从JS中的值定位单个类实例



我正试图从一个类中打印出一组坐标。这个类的每个实例都有3个值:经度、纬度和IP地址。我正在阅读一个日志文件,该文件记录了各种网络攻击的源和目标IP地址。当我从日志文件中读取IP地址时,JS有没有一种方法可以识别IP地址属于类的实例,然后根据它识别的类打印未来的类值?最好的方法是什么?JQuery能解决这个问题吗?

class comp {
constructor(ipa, long, lat){
this.address = ipa;
this.long = long;
this.lat = lat;
ips.push(address);
}
getlong(){
return this.long;
};
getlat(){
return this.lat;
}
getip(){
return this.address;
}
setlatlong(inputLong, inputLat){
this.long = inputLong;
this.lat = inputLat;
return;
}
setip(inputIP){
this.address = inputIP;
}
};
comp1 = new comp('10.0.0.1', '-77.050636', '38.889248');
comp2 = new comp('10.0.0.2', '-78.050636', '39.889248');
//obj = ip addresses
function process(obj){
///
if (ids.includes(obj.id)) {
ids.push(obj.id);
hits.push( { origin : { latitude: comp1.getlat(), longitude: comp1.getlong() },
destination : { latitude: comp2.getlat(), longitude: comp2.getlong() } } );
}
};

我不确定我是否明白你的意思,但你可以使用静态属性。不过,这是一个纯JS解决方案。

您可能也知道这一点,但根据OOP规范,我建议您使用Pascal大小写来命名类,所以我可以相应地重命名它。

纯JS解决方案

class Comp {
// declare static array
static instances = [];
constructor(ipa, long, lat) {
this.address = ipa;
this.long = long;
this.lat = lat;
// to access static properties, use Class.property syntax
// populates the class's instances array with every new instance
Comp.instances.push(this);
ips.push(this.address);
}
// static method to retrieve instance based on IP
static getInstance(ip) {
return Comp.instances.find(v => v.address == ip, null);
}
getlong(){
return this.long;
};
getlat(){
return this.lat;
}
getip(){
return this.address;
}
setlatlong(inputLong, inputLat){
this.long = inputLong;
this.lat = inputLat;
return;
}
setip(inputIP){
this.address = inputIP;
}
};
comp1 = new Comp('10.0.0.1', '-77.050636', '38.889248');
comp2 = new Comp('10.0.0.2', '-78.050636', '39.889248');
console.log(Comp.getInstance('10.0.0.1')); // prints comp1

这是我无法真正理解的部分。检查阵列中的IP,然后再次推送(如果为true(,这是没有意义的。

所以我想你只想每个IP实例化一次,所以…

// source and target objects
function process(src, tgt){
// gets instance of src, if it exists; else creates new one
let comp1 = Comp.getInstance(src.ipa) || new Comp(src.ipa, src.long, src.lat);
// gets instance of tgt, if it exists; else creates new one
let comp2 = Comp.getInstance(tgt.ipa) || new Comp(tgt.ipa, tgt.long, src.lat);
hits.push({
origin: { latitude: comp1.getlat(), longitude: comp1.getlong() },
destination : { latitude: comp2.getlat(), longitude: comp2.getlong() }
});
};

您可以在控制台上执行console.log(Comp.instances)来检查存储的地址和坐标。如果有意义的话,另一个可能的想法是,如果有人试图实例化一个欺骗IP,就会抛出一个异常。

最新更新