Javascript嵌套函数属性继承

Javascript nested function attribute inheritance

本文关键字:属性继承 函数 嵌套 Javascript      更新时间:2023-09-26

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

示例:

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
    }
}

但这并不是我在Player类中需要的Game类的唯一属性。。

更新答案

您可能想阅读有关封装的内容。考虑到您更新的示例,您可以将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"

如果你不想把整个"游戏"功能传递给"玩家",并且你想维护一些变量的隐私,并允许一些玩家方法访问它,我建议如下:

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}
}