我有以下构造函数。
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
关键字指向错误的上下文。如何解决此问题?
答案 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
关键字按词法绑定。因此,它将指向正确的上下文。