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
}
}
但这并不是我在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}
}
相关文章:
- Javascript嵌套函数属性继承
- JavaScript 属性继承
- 为什么函数对象的实例没有继承函数原型属性
- 覆盖上下文.属性和函数
- 主干 where 对作为对象的属性的函数
- 不引人注目地设置属性后函数失败
- 使用onclick调用属性对象函数
- 为什么可以't我的指令从其父作用域继承函数
- 用于更改object.object属性的函数
- Javascript对象属性和函数
- 如何运行由jquery attr添加到onsubmit属性的函数
- 复制不带属性的函数引用
- JavaScript:基于数组中包含的对象属性生成函数
- 嵌套属性作为函数参数
- 单选按钮检查属性在函数 - JavaScript 中失败
- 请解释有关 JavaScript 中的原型属性和函数构造函数的详细信息
- HTML 错误无法设置 null 属性(匿名函数)
- 如何对对象的所有属性调用函数
- Angular 1.4.8/JS:创建构造函数并将属性继承到第三个对象中
- 具有继承属性的函数(可调用)对象