3

我写了一个这样的 jQuery UI 小部件:

$.widget("ns.wid", {
    options: {
        attr1: "something1",
        attr2: {
             "sub_attr": this.__renderList,
             "css": {
                "opacity": '0.58'
              },
        },
    },

    __renderList: function() {
       console.log("I should be invoked through attr2.sub_attr!");
    }
});

现在它不起作用,因为this内部attr2没有引用小部件实例,而是引用了Window. 如何在不直接命名的情况下引用小部件实例?谢谢。

4

2 回答 2

0

我不确定非普通对象是否可以与 jQuery 的小部件一起正常工作,但是。你可以试试这个。

var widgetData = (new class {
    get options() {
        return {
          attr1: "something1",
          attr2: {
             "sub_attr": this.__renderList,
             "css": {
                "opacity": '0.58'
              },
          },
       };
    }

    __renderList() {
       console.log("I should be invoked through attr2.sub_attr!");
    }
});

widgetData.options.attr2.sub_attr();

于 2016-12-01T03:52:21.573 回答
0

在对象的构造函数中,将函数绑定到它的上下文,例如:this._renderList = this._renderList.bind(this)

或者只是:“Sub_att”:this._renderList.bind(this)

于 2016-12-01T03:44:53.683 回答