相关疑难解决方法(0)

如何在回调中访问正确的`this`?

我有一个构造函数,它注册一个事件处理程序:

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', function () {
        alert(this.data);
    });
}

// Mock transport object
var transport = {
    on: function(event, callback) {
        setTimeout(callback, 1000);
    }
};

// called as
var obj = new MyConstructor('foo', transport);
Run Code Online (Sandbox Code Playgroud)

但是,我无法data在回调中访问已创建对象的属性.它看起来this并不是指创建的对象,而是指另一个对象.

我还尝试使用对象方法而不是匿名函数:

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', this.alert);
}

MyConstructor.prototype.alert = function() {
    alert(this.name);
};
Run Code Online (Sandbox Code Playgroud)

但它表现出同样的问题.

如何访问正确的对象?

javascript callback this

1309
推荐指数
12
解决办法
36万
查看次数

如何在Typescript Angular中的另一个函数内调用函数

我是Angular 2的新手。我在Angular中编写了以下代码

export class TestClass {

    constructor() {
        this.initMap();
    }

    initMap() {
        this.marker.addListener('dragend', this.onMarkerDrop);
    }

    onMarkerDrop(event) {
        this.functionTwo(); // Getting error this.functionTwo is not a function
    }

    functionTwo() {

    }
}
Run Code Online (Sandbox Code Playgroud)

注意:在问这个问题之前,我在stackoverflow中搜索了这些链接

'this.function'不是函数-OO JS

this.function不是函数:typescript

角度-this.function不是函数

他们说使用Arrow函数来调用其他成员函数。但是我不知道如何在我的代码中实现他们的建议。可能我对它们的理解不正确。

我想要您的帮助,如何使用functionOne();中的箭头函数调用this.functionTwo();

谢谢您的帮助。

javascript google-maps typescript ionic-framework angular

5
推荐指数
2
解决办法
6059
查看次数