如何从另一个对象调用对象的方法?

时间:2017-07-30 19:47:08

标签: javascript oop ecmascript-6

我正在使用ES6类创建自定义UI组件,如下所示:

class Dropdown {

    constructor(dropdown) {
        this.dropdown = dropdown;
        this._init();
    }

    _init() {
        //init component
    }

    setValue(val) {
        //"public" method I want to use from another class
    }
}

当页面加载时,我启动这样的组件:

let dropdown = document.querySelectorAll(".dropdown");
if (dropdown) {
    Array.prototype.forEach.call(dropdown, (element) => {
        let DropDownEl = new Dropdown(element);
    });
}

但是现在我需要从另一个类中访问其中一个类的方法。在这种情况下,我需要访问一个方法来设置下拉列表的值 基于URL参数,所以我想做类似的事情:

class SearchPage {
//SearchPage is a class and a DOM element with different components (like the dropdown) that I use as filters. This class will listen to the dispached events
//from these filters to make the Ajax requests.

    constructor() {
        this._page = document.querySelector(".search-page")
        let dropdown = this._page.querySelector(".dropdown);
        //Previously I import the class into the file            
        this.dropdown = new Dropdown(dropdown);
    }

    setValues(val) {

        this.dropdown.setValue(val);
        //Set other components' values...
    }

}

但是当我创建此实例时,会在页面中添加另一个下拉菜单,这是我不想要的。

我认为另一种方法是以这种方式创建组件,在其他组件中创建,而不是像第一段代码中那样。这是一种有效的方式吗?我应该创建另一个继承自原始类的Dropdown类吗?

1 个答案:

答案 0 :(得分:2)

一个简单的解决方案是将Dropdown实例存储在元素上以避免重新创建它:

class Dropdown {
    constructor(element) {
        if (element.dropdown instanceof Dropdown)
            return element.dropdown;
        this.element = element;
        element.dropdown = this;

        //init component
    }
    …
}
相关问题