在构造函数内部访问构造函数的属性

时间:2020-02-19 08:11:50

标签: javascript jquery ecmascript-6 constructor functional-programming

我有以下构造函数。

function Tablo() {
    this.kayit_id = 0;
    this.rapor_instanse = 'rapor';
    this.kosul_durum = null;
    this.tablo_nesne = null;
    this.tablo_getir = function() {
        this.tablo_nesne = new Handsontable(
            document.getElementById(this.rapor_instanse), {
                afterGetColHeader: this.arama_filtre_element_ekle,
                beforeOnCellMouseDown: this.doNotSelectColumn,
                columnSorting: true,
                rowHeaders: true,
                currentRowClassName: 'currentRow',
                wordWrap: false,
                licenseKey: 'non-commercial-and-evaluation',
                manualColumnResize: true,
                manualRowResize: true,
                afterSelectionEnd: function(r, c, r2, c2) {
                    let suppliedarrayobject = this.tablo_nesne.getSourceDataAtRow(
                        this.tablo_nesne.toPhysicalRow(r)
                    );
                    this.kayit_id = suppliedarrayobject.kayit_id;
                }
            }
        );
    };
}

我需要访问和修改tablo_nesne函数中的属性 afterSelectionEnd 。但是,this关键字指向错误的上下文。如何解决此问题?

2 个答案:

答案 0 :(得分:2)

您可以通过在tablo_getir上调用bind(this)将其绑定到tablo_getir以便在Tablo上访问它

或声明一个self = this 在您的Tablo 并在您的tablo_getir

中使用它

或者您可以将tablo_getir设置为箭头函数,它应该自动绑定

答案 1 :(得分:1)

ES6中惯用的解决方案是使用arrow function

function Tablo() {
    this.kayit_id = 0;
    this.rapor_instanse = 'rapor';
    this.kosul_durum = null;
    this.tablo_nesne = null;
    this.tablo_getir = function() {
        this.tablo_nesne = new Handsontable(
            document.getElementById(this.rapor_instanse), {
                afterGetColHeader: this.arama_filtre_element_ekle,
                beforeOnCellMouseDown: this.doNotSelectColumn,
                columnSorting: true,
                rowHeaders: true,
                currentRowClassName: 'currentRow',
                wordWrap: false,
                licenseKey: 'non-commercial-and-evaluation',
                manualColumnResize: true,
                manualRowResize: true,
                afterSelectionEnd: (r, c, r2, c2) => { // This is an arrow function.
                    let suppliedarrayobject = this.tablo_nesne.getSourceDataAtRow(
                        this.tablo_nesne.toPhysicalRow(r)
                    );
                    this.kayit_id = suppliedarrayobject.kayit_id;
                }
            }
        );
    };
}

箭头函数中的this关键字按词法绑定。因此,它将指向正确的上下文。