【问题标题】:javascript prototype function gets ignoredjavascript原型函数被忽略
【发布时间】:2017-01-24 11:22:08
【问题描述】:

我有一个

“无法读取未定义的属性‘绑定’”

我的 javascript 对象中的问题。如何强制执行绑定?

当我调用这个函数时会发生这种情况:

function ViewportDatasource(mockServer) {
        this.mockServer = mockServer;        
        this.connectionId =this.mockServer.connect(this.eventListener.bind(this));
    }

即使eventListener 已在原型函数中正确定义

 ViewportDatasource.prototype.eventListener = function (event) {
        switch (event.eventType) {
            case 'rowCountChanged':
                this.onRowCountChanged(event);
                break;
            case 'rowData':
                this.onRowData(event);
                break;
            case 'dataUpdated':
                this.onDataUpdated(event);
                break;
        }
    };

我能做什么?

为了回答 Daniel 的问题,这里调用了实例:

 function setRowData($http) {
        // set up a mock server - real code will not do this, it will contact your
        // real server to get what it needs
        var mockServer = new MockServer();
        $http.get('data.json').then(function(response){
            mockServer.init(response.data);
        });

        var viewportDatasource = new ViewportDatasource(mockServer);
        table.api.setViewportDatasource(viewportDatasource);
        // put the 'size cols to fit' into a timeout, so that the scroll is taken into consideration
        setTimeout(function () {
            table.api.sizeColumnsToFit();
        }, 100);
    }

这个函数在调用者中的 ag-grid 对象准备好后执行

【问题讨论】:

  • 你是如何构建你的实例的?什么时候?

标签: javascript prototype-programming


【解决方案1】:
function ViewportDatasource(mockServer) {
    //the this operator here is undefined. function is not of object.
    this.mockServer = mockServer;        
    this.connectionId =this.mockServer.connect(this.eventListener.bind(this));
}

只有在将函数绑定到对象时才应该使用 this 运算符,在这种情况下 this 运算符才有意义。在上面的例子中它没有。

【讨论】:

  • 我该如何纠正它?那我怎样才能引用对象本身呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 2021-07-04
相关资源
最近更新 更多