Javascript 嵌套函数属性继承

Javascript nested function attribute inheritance

我试图在嵌套函数中使用函数的属性,但我不知道如何在不传递父函数的情况下使用。

示例:

function foo() {
    this.baz = 'baz'
    this.bar = new bar()
}

function bar() {
    this.bla = 'bla'
}

bar.prototype.func = function() {
    console.log(...) // this should return 'baz' (attr baz of foo())
}

到目前为止我试过这个:

function foo() {
    this.baz = 'baz'
    this.bar = new bar(this)
}

function bar(foo) {
    this.bla = 'bla'
    this.foo = foo
}
bar.prototype.func = function() {
    console.log(this.foo.baz)
}

有什么好的模式可以做到这一点吗?因为我的解决方法一团糟

编辑:

因为你们中的一些人想要一个更真实的例子:

function Game() {
    this.world = {
        x: 200,
        y: 300
    }
    this.players = {
        one: new Player()
        two: new Player()
    }
}

function Player() {
    this.size = {x:1,y:2}
    this.position = {
        x: world.x - this.size.x, // i need to access games world attribute
        y: 0
    }
}

但这不是我在播放器 class 中需要的游戏 class 的唯一属性 class..

更新答案

您可能想阅读有关 encapsulation 的内容。鉴于您更新的示例,您将 Game 的引用传递给每个 Player 实例是合理的,如下所示:

function Game() {
    this.world = {
        x: 200,
        y: 300
    }
    this.players = {
        one: new Player(this),
        two: new Player(this)
    }
}

function Player(game) {
    this.game = game;
    this.size = {x:1,y:2}
    this.position = {
        x: game.world.x - this.size.x, // i need to access games world attribute
        y: 0
    }
}
Player.prototype.anotherFunction = function() {
  console.log(this.game); // Also has access to `this.game`
}

正如 Vld@ 所说,可能有更好的方法来完成您在此示例中尝试做的事情,但我怀疑这是一个更普遍的问题。

原回答

完成您想要做的事情的一种方法是继承,如下所示:

function Foo() {
  this.baz = 'baz';
}
function Bar() {
  this.bla = 'bla';
  Foo.call(this);
}
Bar.prototype = Object.create(Foo.prototype);

console.log(new Bar().baz); // "baz"

如果您不想将整个 "Game" 函数传递给 "Player",并且您还想保持某些变量的隐私并允许某些播放器方法访问它,我推荐以下内容:

function Game() {

    // Declare private variables as 'var' here

    this.world = {
        x: 200,
        y: 300
    }
    this.players = {
        one: new Player()
        two: new Player()
    }

    // The following players methods will have access to 
    // both public and private interface of Game 
    this.players.one.position = {
        x: this.world.x - this.players.one.size.x, 
        y: 0
    }
    this.players.two.position = this.players.one.position;
}

function Player() {
   // Declare private variables for player as 'var' here 

   this.size = {x:1,y:2}
}