简体   繁体   English

在对象中引用自身的匿名功能键Javascript

[英]In Object refer to itself anonymous function key Javascript

I have this object: 我有这个对象:

var crudConfig = function($wizard, $formModal, $deleteModal) {

'use strict';

return {


    handleOnShowFormModal : function() {

        $formModal.on('show.bs.modal', function(event) {
               ...................
                    this.fillForms(data);
               ....................
        });

        return this;
    },
    fillForms : function(data) {
        //do stuff
        return this;
    }
 }
}

The problem appears when I call the fillForms with the param. 当我用参数调用fillForms时出现问题。

Uncaught TypeError: this.fillForms is not a function

As the fillForms key is an anonymous function how can I call it from inside the object? 由于fillForms键是一个匿名函数,如何从对象内部调用它? On other relative questions I only found how to refer itself if the key has a string value and the I call like this: this.fillForms . 在其他相关问题上,我仅发现如果键具有字符串值并且我这样调用,则如何引用自身: this.fillForms

this within the callback references the $formModal element. this在回调中引用$formModal元素。 What you need to do is store this that refer to the object in a variable before the event listener is called and use the variable within the callback to access the object. 你需要做的就是保存this引用对象的变量的事件监听器被调用,并使用回调中的变量来访问对象之前。

Just like this: 像这样:

handleOnShowFormModal : function() {
  var _this = this
  $formModal.on('show.bs.modal', function(event) {
    _this.fillForms(data); 
  });

  return this;
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM