gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:29:25 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com