如果在 javascript 中有其名称的字符串,如何访问 class?

How to access a class if you have a string of its name in javascript?

在 javascript 中,如果我有 2 个字符串 myAppmy-app 并且被告知 myApp 实际上是 class 的名称HTMLElement,而 my-app 是 class 的标记名,我如何使用 JavaScript 来验证(假设 class 已经定义)?

基本上,如果已经真正定义了,测试应该会通过

class myApp extends HTMLElement {
    constructor() {
        super();
    }
}

customElements.define('my-app', myApp); 

基本上,它需要检查 myApp 是一个 class 并且确实扩展了 HTMLElement(尽管它可能会扩展其他内容,例如 Polymer.Element,和病房,但最终,它必须扩展 HTMLElement).

其次,它必须检查 my-app 是那个 class 的标签名称。

如何在 javascript 中完成?

我试过eval("myApp")但没用。

要检查 classextends HTMLElement 是否存在,应在与 class 相同的范围内执行检查,方法是尝试声明 myApp 使用 const 应该抛出 SyntaxError 或使用 console.assert().

验证第一部分后,您可以创建元素并检查创建元素的 .is 属性 或 .tagName

class myApp extends HTMLElement {
    constructor() {
        super();
    }
}

customElements.define('my-app', myApp); 

// string
let str = "myApp";
// get the object, if the object exists
const myApp_ = new Function(`return ${str}`)();
// check if `myApp` exists
console.assert(myApp_ === void 0
, myApp_
, [`${myApp_} is defined`
  , new RegExp(`${str} extends HTMLElement`).test(`${myApp_}`)]);

好的,我想通了,我可以做到

    var worked = false;
    var claimedClassName = 'myApp';
    var claimedElementName = 'my-app'; 

    try {
        const r = new Function(`return ${claimedClassName}`)();
        if (!(r.prototype instanceof HTMLElement)) {
            throw new Error('Class is not instance of HTMLElement');
        }
        var a = new r();
        if (a.tagName.toLowerCase() != claimedElementName.toLowerCase()) {
            throw new Error('Tagname does not match');
        }
        worked = true;
    } catch (err) {
        alert(err.message + "\n" + err.stack);
    }

    if (worked) alert("pass!")
    else alert("fail!");

您可以使用 customElements.get() 从标签名称中获取自定义元素 class。

class myApp extends HTMLElement {
  constructor() {
    super()
  }
}
customElements.define( 'my-app', myApp )

console.log( customElements.get( 'my-app' ) === myApp )  //true