Javascript回调与对象结构 [英] Javascript Callbacks with Object contructor

查看:142
本文介绍了Javascript回调与对象结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这可能是JavaScript下的最愚蠢的问题。但我无能为力。下面是一个函数,创建和对象和调用回调(不是确切的代码,但类似的东西)。

Ok, this might be the stupidest question asked under JavaScript. But I am clueless. 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 在新创建对象的上下文中访问回调,调用来调用回调。

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]);
    }); 
}

这篇关于Javascript回调与对象结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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