[英]Javascript passing parameter with arrow function
I have a class for creating a jquery datatable, it works but I'm having some issue with the following piece of code: 我有一个用于创建jquery数据表的类,它可以工作,但是下面的代码存在一些问题:
let table = $("#" + this.name).DataTable();
table.on( 'click', 'tr td.details-control', function() {
let detailRows = [];
let tr = $(this).closest('tr');
let row = table.row( tr );
let idx = $.inArray( tr.attr('id'), detailRows );
if ( row.child.isShown() ) {
tr.removeClass( 'details' );
row.child.hide();
detailRows.splice( idx, 1 );
}
else {
tr.addClass( 'details' );
let rowData = table.row(tr).data();
row.child(this.formatChildRows( rowData ) ).show();
if ( idx === -1 ) {
detailRows.push( tr.attr('id') );
}
}
} );
Because of the way "this" works in javascript, the function formatChildRows is no longer found as this no longer refers to the class but to the table row, I solved this by changing the code like so: 由于“ this”在javascript中的工作方式,不再找到函数formatChildRows,因为它不再指向类而是指向表行,我通过更改代码来解决此问题,如下所示:
table.on( 'click', 'tr td.details-control', (event) => {
...
} );
The function now runs but the "table" variable is no longer accessible as it is undefined in the arrow function. 该函数现在运行,但是“ table”变量不再可用,因为在箭头函数中未定义该变量。
I tried plenty of things like: 我尝试了很多类似的事情:
evt => function(table) {}
instead of: 代替:
(event) =>
I thought this might work but the code inside the function is no longer being executed for some reason. 我以为这可能有效,但是由于某种原因该函数内的代码不再被执行。
Any ideas? 有任何想法吗?
This should work: 这应该工作:
const self = this;
table.on( 'click', 'tr td.details-control', function (event){
row.child(self.formatChildRows( rowData ) ).show();
...
} );
But if it is possible you should avoid this
keyword, for example you should refer directly to object objectName.formatChildRows()
. 但是,如果有可能应避免使用this
关键字,例如,应直接引用对象objectName.formatChildRows()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.