【问题标题】:Js: How is the cleanest way to identify which child class is it?Js:如何最简洁地识别它是哪个子类?
【发布时间】:2017-02-20 00:30:35
【问题描述】:

我有这个代码,每个文件中的每个类:

a.js

Import B from './b'
Import C from './c'

class A {

    constructor() {
        this.child = {
            b : [],
            c : []
        };
    }

    setChild(child) {

        if (child instanceof B) {
            this.child.b.push();
            return true;
        }

        if (child instanceof C) {
            this.child.b.push();
            return true;
        }

        return false;
    }

    getBChilds() {

        return this.child.b;
    }

    getCChilds() {

        return this.child.c;
    }
}

b.js

Import A from './a'

class B extends A {

}

c.js

Import A from './a'

class C extends A {

}

而测试代码可以是:

test.js

let a = new A();

console.log(a.setChild(new B()));
console.log(a.setChild(new B()));
console.log(a.setChild(new C()));
console.log(a.setChild(new A()));
console.log(a.setChild(new (function B(){})));

正确答案在哪里:

true
true
true
false
false

问题是我如何检测setChild() 的变量是否是一个有效的类

但我认为“递归导入”不是一个好习惯。所以我认为它们是更清洁/更好的方法。

我试过了:

switch (child.constructor.name) {

    case "B":
        this.child.b.push();
        return true;
    case "C":
        this.child.b.push();
        return true;
}

return false;

但我可以用new function B(){}; 破解它。所以不是解决问题。

PD:如果编译器无法解决“递归导入”,我可以删除它并使用:

child instanceof require('./b')
child instanceof require('./c')

但是这样好吗?

【问题讨论】:

  • 您对“是一个有效的类”的标准是什么?你考虑过child.constructor === B吗?虽然这也可以伪造,并且可能会故障转移帧。
  • 只能通过“b.js”的“B”类和“c.js”的“C”类。如果另一个类即使具有相同的名称,也不要将其添加到列表中。喜欢:new function B(){};。我得到孩子instanceof require('./b') 喜欢最好的方式。但我不确定这是否干净。
  • 为什么您认为递归导入是一种不好的做法?您似乎过分担心您的代码是否“可破解”。 JavaScript 是一种动态类型语言。你越是使用严格的类类型,你的代码就会变得越糟糕。
  • 请详细说明您的最终目标。你想用它做什么?这将有助于找到合适的模式。上面的代码将在 B 和 C 中创建 this.child。这是一种可取的行为吗?您是否真的想让 B 实例具有 getBChilds 将返回一组与 A 实例不同的对象?顺便说一句,constructor.name is not minifiable.

标签: javascript import ecmascript-6


【解决方案1】:

我觉得,我推荐instanceof方法和传递构造函数。

setChild(origin, child) {

    if (child instanceof origin) {
        this.child.b.push();
        return true;
    }

    if (child instanceof origin) {
        this.child.b.push();
        return true;
    }

    return false;
}
console.log(a.setChild(B,new B()));
console.log(a.setChild(B,new B()));
console.log(a.setChild(C,new C()));
console.log(a.setChild(A,new A()));
console.log(a.setChild(B,new (function B(){})));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    相关资源
    最近更新 更多