簡體   English   中英

帶箭頭功能的Javascript傳遞參數

[英]Javascript passing parameter with arrow function

我有一個用於創建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') );
            }
        }
    } );

由於“ this”在javascript中的工作方式,不再找到函數formatChildRows,因為它不再指向類而是指向表行,我通過更改代碼來解決此問題,如下所示:

table.on( 'click', 'tr td.details-control', (event) => {
    ...
} );

該函數現在運行,但是“ table”變量不再可用,因為在箭頭函數中未定義該變量。

我嘗試了很多類似的事情:

evt => function(table) {}

代替:

(event) =>

我以為這可能有效,但是由於某種原因該函數內的代碼不再被執行。

有任何想法嗎?

這應該工作:

const self = this;
table.on( 'click', 'tr td.details-control', function (event){
    row.child(self.formatChildRows( rowData ) ).show();
    ...
} );

但是,如果有可能應避免使用this關鍵字,例如,應直接引用對象objectName.formatChildRows()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM