我有以下构造函数。
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关键字指向错误的上下文。我该如何解决这个问题?
发布于 2020-02-19 08:19:39
您可以通过在tablo_getir上调用bind( this )来将其绑定到tablo_getir以访问Tablo
或在Tablo中声明self =,并在tablo_getir中使用它
或者您可以将tablo_getir作为箭头函数,它应该自动绑定这一点。
发布于 2020-02-19 08:36:08
ES6中的惯用解决方案是使用箭头函数。
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关键字是按词汇绑定的。因此,它将指向正确的上下文。
https://stackoverflow.com/questions/60295661
复制相似问题