我有下面的JavaScript代码段。简而言之,我想要实现的目标是什么;检查传递给函数的参数是否是某些预定类的实例的方法。我知道我可以使用
if(obj instanceof className){ /* do stuff * / } else{ /* other things */ }语句但是代码很庞大,特别是如果我有一堆类要测试的话。简而言之,我怎样才能实现下面代码的尝试?谢谢大家。
class A {
constructor(name) {
this._name = name;
}
}
class B {
constructor(name) {
this._name = name;
}
}
class C {
constructor(name) {
this._name = name;
}
}
let allTemplates = ['A', 'B', 'C', 'Object']; //available classes
let a = new A('A class');
let b = new B('B class');
let c = new C('C class');
function seekTemplateOf(obj) {
/**find if @arg obj is an instance of any
** of the classes above or just an object
**@return string "class that obj is instance of"
**/
return allTemplates.find(function(template) {
return obj instanceof window[template];
/*Thought that ^^ could do the trick?*/
});
}
console.log(seekTemplateOf(a));
/*"^^ Uncaught TypeError: Right-hand side of 'instanceof' is not an object"*/

答案 0 :(得分:1)
将字符串更改为引用:
var dates = ["02/07/2018-02/07/2018", "02/05/2018-02/07/2018", "02/06/2018-02/06/2018", "02/08/2018-02/08/2018"];
var overlaps = checkOverlaps(dates);
console.log("overlaps", overlaps);
var dates1 = ["02/07/2018-02/07/2018", "02/08/2018-02/10/2018", "02/19/2018-02/20/2018", "02/21/2018-02/21/2018"];
var nonoverlaps = checkOverlaps(dates1);
console.log("nonoverlaps", nonoverlaps);
var dates2 = ["02/07/2018-02/07/2018", "02/07/2018-02/10/2018"]; /* 2nd range starts on the end of the first range */
var overlaps2 = checkOverlaps(dates2);
console.log("overlaps", overlaps2);
function checkOverlaps(dates) {
var o = false;
for (var key1 in dates) {
var cDateArr = dates[key1].split("-");
var d1 = new Date(cDateArr[0]);
var d2 = new Date(cDateArr[1]);
for (var key2 in dates) {
//make sure not comparing to own self
if (key1 != key2) {
var cDateArrB = dates[key2].split("-");
var dB1 = new Date(cDateArrB[0]);
var dB2 = new Date(cDateArrB[1]);
if (
(d1 < dB1 && d2 > dB1) ||
(d1 < dB2 && d2 > dB2) ||
cDateArr[0] == cDateArrB[0] ||
cDateArr[0] == cDateArrB[1] ||
cDateArr[1] == cDateArrB[0] ||
cDateArr[1] == cDateArrB[1]
) {
o = true;
}
}
}
}
return o;
}
然后检查对象构造函数是否等于:
let allTemplates = [A, B, C, Object];
或者(如果某些原型黑客忘记设置const obj = new A;
const objClass = allTemplates.find(c => obj.constructor === c);
),您可能会获得明确的原型:
constructor
或者你可以简单地使用const obj = new A;
const objClass = allTemplates.find(c => Object.getPrototypeOf(obj) === c.prototype);
:
instanceof
答案 1 :(得分:1)
您可以使用对象作为模板并再次检查给定对象。
class A { constructor(name) { this._name=name; } }
class B { constructor(name) { this._name=name; } }
class C { constructor(name) { this._name=name; } }
let allTemplates = { A, B, C, Object };
let a = new A('A class');
let b = new B('B class');
let c = new C('C class');
function seekTemplateOf(obj) {
return Object.keys(allTemplates).find(template => obj instanceof allTemplates[template]);
}
console.log(seekTemplateOf(a));