从兄弟姐妹那里调用其他对象的方法的正确方法

时间:2015-11-05 12:30:13

标签: javascript oop

我有几个用以下结构构造的javascript对象。我不知道这是否正确或结构是否不可推荐,但我想知道如何从指定地点调用该方法:

function Graphic_Interface (){
    var btn = document.querySelector(".btn");
    btn.addEventListener("click", function(){
        //I want to call game > obj > doSomething() from here; how can I do it?
    })
}
function Another_Object(){
    this.doSomething = function(){
        console.log('doing something');
    };
}
function Game (){
    var gi = new Graphic_Interface();
    var obj = new Another_Object();
}
var game = new Game();

有可能吗?施工权对吗?有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

如果我理解正确(假设Game用作构造函数),您希望将Game对象传递给Graphic_Interface

这样的东西
function Graphic_Interface (game){
    var btn = document.querySelector(".btn");
    btn.addEventListener("click", function(){
        game.obj.do_something();
    })
}
function Another_Object(){
    this.doSomething = function(){
        console.log('doing something');
    };
}
function Game (){
    var gi = new Graphic_Interface(this);
    this.obj = new Another_Object(); // Note saving as member
}
相关问题