Javascript Can';调用回调时不访问对象属性
我知道Javascript Can';调用回调时不访问对象属性,javascript,oop,Javascript,Oop,我知道apinstance是有效的,就好像我在构造函数中提醒实例它显示为对象一样。由于某种原因,当调用tokenHandler回调时,此.api突然未定义。。你知道为什么吗?JavaScript中的OOP太令人沮丧了…当你这么做的时候 function Push(apiInstance) { this.api = apiInstance; // If I alert() here this is a valid object this.pushNotification = win
apinstance
是有效的,就好像我在构造函数中提醒实例它显示为对象一样。由于某种原因,当调用tokenHandler回调时,此.api
突然未定义。。你知道为什么吗?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 */);
实际上,您正在传递函数对象tokenHandler
,它不知道它已绑定到当前对象。因此,当它被register
函数调用时,由于它没有绑定到任何对象,JavaScript将作为this
传递全局对象(在严格模式下,它将传递未定义的
)。为了避免这种情况,您需要显式地将当前对象与函数对象绑定,如下所示
this.pushNotification.register(
this.tokenHandler,
this.errorHandler, ...);
问题在于:
this.pushNotification.register(
this.tokenHandler.bind(this),
this.errorHandler.bind(this), ...);
它只是一个函数本身,函数不知道它所属的位置以及它的上下文应该是什么。要解决此问题,您可以应用以下方法:
this.tokenHandler
闭包的使用将确保使用
self
上下文调用令牌处理程序
,这是推送
的一个实例,这是因为javascript中的作用域是在函数级别上完成的
在这和平的法典中:
var self = this;
this.pushNotification.register(
function (token) {
self.tokenHandler(token);
},
“this”-是功能推送的范围。因此,您可以尝试下一步:
function Push(apiInstance) {
this.api = apiInstance; // If I alert() here this is a valid object
}
在这段代码中,api-将不在函数的作用域中,而是在函数Push的“全局作用域”中
var api = {};
function Push(apiInstance) {
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) {
api.registerDevice(token); // Suddenly this.api is undefined
};
var push = new Push(/* in my production code this is a valid object */);