使用对象构造函数的Java语言回调 [英] Javascript Callbacks with Object constructor

查看:81
本文介绍了使用对象构造函数的Java语言回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一个创建并对象并调用回调的函数(不是确切的代码,而是类似的东西)。

Following is a function which creates and object and call the callback (not the exact code but something similar).

myObject = function(callback){

    var tmpThis = this;
    this.accounts = [];
    tmpThis.accounts[0] = 1;
    tmpThis.accounts[1] = 2;
    callback();
}

function caller(){
    var newMyObject = new myObject(function() {
        alert(newMyObject.accounts[1]);
    }); 
}

newMyObject 未定义在回调函数中。有没有办法我可以访问它。我读过类似的问题,但没有一个简单地解释原因。

newMyObject is undefined inside the callback function. Is there a way I can access it. I read similar questions but none simply explains why.

我可以通过在第二个参数中将创建的对象传递回回调函数来修复它。但是我认为这是一种黑客手段,而不是正确的方法。

I can fix it by passing back the created object in a second parameter to the callback function. But I think its a hack rather than the proper way.

推荐答案

您可以使用 this 在新创建的对象的上下文中访问回调,并 call 调用回调。

You can use this to access the callback in the context of the newly create object, and call to invoke the callback.

myObject = function(callback){

    var tmpThis = this;
    this.accounts = [];
    tmpThis.accounts[0] = 1;
    tmpThis.accounts[1] = 2;
    callback.call(this);
}

function caller(){
    var newMyObject = new myObject(function() {
        alert(this.accounts[1]);
    }); 
}

这篇关于使用对象构造函数的Java语言回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆