Javascript使用bind而不覆盖这个

时间:2017-05-18 18:23:37

标签: javascript jquery

采用这个使用" widgetManager"的示例将事件绑定到所有手风琴的对象:

widgetManager = {
    name : 'widgetManager',
    initiate : function(){
        $('.accordion').accordion({
            onClosing : this.onCloseAccordion.bind(this.name),
        })
    },
    onCloseAccordion : function(){
        console.log(name); //I want the event to receive the manager name
        console.log(this); //But still be able to know which accordion was clicked
    }
}
widgetManager.initiate();

如果我将某些东西绑定到手风琴的onClosing事件上,它将失去对自身的引用(手风琴正在关闭),但我还需要一种方法来传递&# 39;名称'属于该功能。

也许bind不是我想要的,但有一种简单的方法可以解决这个问题吗?

我想更好的措辞是,如何将对象传递给函数而不覆盖函数的范围' s this

如果有帮助或改变任何内容,我会使用Semantic UI的手风琴,但该事件没有参数https://semantic-ui.com/modules/accordion.html#/settings

1 个答案:

答案 0 :(得分:1)

您只需引用widgetManager.name即可获取名称。

widgetManager = {
    name : 'widgetManager',
    initiate : function(){
        var theManager = this;
        $('.accordion').accordion({
            onClosing : this.onCloseAccordion.bind(this),
        })
    },
    onClosing : function(){
        console.log(widgetManager.name); //I want the event to receive the manager name
        console.log(this); //But still be able to know which accordion was clicked
    }
}
widgetManager.initiate();

如果你想要更通用的东西,你应该使用构造函数来创建不同的管理器。

function widgetManager(name) {
    this.name = name;
    this.initiate = function() {
        $('.accordion').accordion({
            onClosing: this.onCloseAccordion.bind(this);
        });
        return this; // For fluent interface
    };
    this.onCloseAccordion = function() {
        console.log(name);
        console.log(this);
    };
};

然后你就这样使用它:

var theWidgetManager = new widgetManager("widgetManager");
theWidgetManager.initiate();