首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在构造函数中访问构造函数的属性

在构造函数中访问构造函数的属性
EN

Stack Overflow用户
提问于 2020-02-19 08:11:50
回答 2查看 76关注 0票数 1

我有以下构造函数。

代码语言:javascript
复制
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关键字指向错误的上下文。我该如何解决这个问题?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-19 08:19:39

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

或在Tablo中声明self =,并在tablo_getir中使用它

或者您可以将tablo_getir作为箭头函数,它应该自动绑定这一点。

票数 2
EN

Stack Overflow用户

发布于 2020-02-19 08:36:08

ES6中的惯用解决方案是使用箭头函数

代码语言:javascript
复制
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关键字是按词汇绑定的。因此,它将指向正确的上下文。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60295661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档