javascript原型函数被忽略了

时间:2017-01-24 11:22:08

标签: javascript prototype-programming

我有

"无法读取属性' bind'未定义"

在我的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对象准备就绪后执行

1 个答案:

答案 0 :(得分:0)

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));
}

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