实例化为字符串时,Item不是构造函数

时间:2017-01-11 21:16:36

标签: javascript typescript

我正在尝试创建一个对象的实例,但我得到了:

  

TypeError:window [comps [i]]不是构造函数

这种方法正在发生(在for循环中):

private getComponents() {
    let comp = this._element.getAttribute('component');
    if (!comp) {
        comp = this._element.getAttribute('data-component');
    }
    let comps = comp.split(' ');
    for (let i = 0, l = comps.length; i < l; i++) {
        this._components.push(new window[comps[i]]());
    }
}

这是它试图实例化的类,但不是

class TestComponent extends Component {
    public click() {
        alert('you clicked me');
    }
}

组件类看起来像这样:

class Component {

    public constructor() {

    }

}

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
class Component {
    constructor() {
      console.log('Component created');
    }
}

class TestComponent extends Component {
    constructor() {
      super();
    }
  
    click() {
        alert('you clicked me');
    }
}


this._components = new Array();

getComponents();

function getComponents() {
  // note TestComponent not 'TestComponent'
    let comps = [TestComponent];
  
    for (var i = 0; i< comps.length; i++) {
      this._components.push(new comps[i]);
      this._components[i].click();
    } 
}
&#13;
&#13;
&#13;