Javascript function objects, this keyword points to wrong object

前端 未结 4 1243
梦谈多话
梦谈多话 2021-01-19 19:26

I\'ve got a problem concerning the javascript \"this\" keyword when used within a javascript functional object. I want to be able to create an object for handling a Modal po

4条回答
  •  暖寄归人
    2021-01-19 19:41

    You need to create a closure to trap the this context, I tend to use an anonymous function to do this as follows:-

    CreateItemModal.prototype.show = function() {
        this.$wrapper.dialog({
            buttons: {
                // this crashes because this is not the current object here
                Cancel: (function(self) {
                  return function() { self.close.apply(self, arguments ); }
                })(this);
            }
        });
    };
    

提交回复
热议问题