在对象中引用自身匿名函数键 Javascript
In Object refer to itself anonymous function key Javascript
我有这个对象:
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;
}
}
}
当我用参数调用fillForms时出现问题。
Uncaught TypeError: this.fillForms is not a function
由于 fillForms 键是一个匿名函数,我如何从对象内部调用它?在其他相关问题上,我只发现如果键有一个字符串值并且我这样调用:this.fillForms
.
回调中的 this
引用 $formModal
元素。您需要做的是在调用事件侦听器之前存储 this
引用变量中的对象,并在回调中使用该变量来访问该对象。
就像这样:
handleOnShowFormModal : function() {
var _this = this
$formModal.on('show.bs.modal', function(event) {
_this.fillForms(data);
});
return this;
},
我有这个对象:
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;
}
}
}
当我用参数调用fillForms时出现问题。
Uncaught TypeError: this.fillForms is not a function
由于 fillForms 键是一个匿名函数,我如何从对象内部调用它?在其他相关问题上,我只发现如果键有一个字符串值并且我这样调用:this.fillForms
.
this
引用 $formModal
元素。您需要做的是在调用事件侦听器之前存储 this
引用变量中的对象,并在回调中使用该变量来访问该对象。
就像这样:
handleOnShowFormModal : function() {
var _this = this
$formModal.on('show.bs.modal', function(event) {
_this.fillForms(data);
});
return this;
},