javascript - 调用回调时无法访问对象属性

标签 javascript oop

function Push(apiInstance) {
    this.api = apiInstance; // If I alert() here this is a valid object
    this.pushNotification = window.plugins.pushNotification;

    if ( device.platform == 'android' || device.platform == 'Android' )
    {
        this.pushNotification.register(
            this.successHandler,
            this.errorHandler, {
                "senderID":"",
                "ecb":"onNotificationGCM"
            });
    }
    else
    {
        this.pushNotification.register(
            this.tokenHandler,
            this.errorHandler, {
                "badge":"true",
                "sound":"true",
                "alert":"true",
                "ecb":"onNotificationAPN"
            });
    }
}

Push.prototype.tokenHandler = function (token) {
    this.api.registerDevice(token); // Suddenly this.api is undefined
};

var push = new Push(/* in my production code this is a valid object */);

我知道 apiInstance 是有效的,就好像我在构造函数中提醒实例它显示为一个对象一样。出于某种原因,当调用 tokenHandler 回调时 this.api 突然未定义。任何想法为什么? JavaScript 中的 OOP 是如此令人沮丧......

最佳答案

当你做的时候

this.pushNotification.register(
    this.tokenHandler,
    this.errorHandler, ...);

您实际上是在传递函数对象 tokenHandler 并且它不知道它已绑定(bind)到当前对象。所以当它被 register 函数调用时,因为它没有绑定(bind)到任何对象,JavaScript 将把全局对象作为 this 传递(在严格模式下它将传递 未定义)。为避免这种情况,您需要使用 Function.prototype.bind 将当前对象与函数对象显式绑定(bind)。像这样

this.pushNotification.register(
    this.tokenHandler.bind(this),
    this.errorHandler.bind(this), ...);

关于javascript - 调用回调时无法访问对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23473852/

相关文章:

oop - 对象与其成员之间的通信

javascript - 从div中的另一个页面访问html元素

java - 为什么我不能在 html 上启动我的 LibGDX 项目?

javascript - 无法读取对象数组上 null 的三元运算符的属性

javascript - 有人用过 Sigma Grid(基于 Javascript 的可编辑数据网格)吗?

c++ - 设计面向对象的同步接收机和发射机

php - PHP类速成类

javascript - 在函数内部使用 "this"- nodeJS

c++ - 构造函数将运行但不能从其他文件运行

oop - Lua检查方法是否存在