我試圖在嵌套函數中使用函數的屬性,但我不知道如何,而不通過父函數。Javascript嵌套函數屬性繼承
例如:
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())
}
到目前爲止我tryed這一點:
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)
}
是否有一個良好的模式來做到這一點?因爲我的解決方法是一個爛攤子
編輯:
由於一些你想要一個更現實生活中的exapmle:
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類..
這似乎是關於JavaScript範圍如何工作的一半問題,以及關於繼承如何工作的一半問題。也許如果你給了更多的現實生活中的例子,我們可以提出更好的建議,以便做出你想做的事情。現在看來,我的迴應是「僅僅通過一個'foo'引用'bar' – brianvaughn 2015-04-04 16:25:03
在你的例程中,'bar'不會從'foo'繼承,'bar'上沒有可以訪問的原型屬性'foo'的屬性,你在第一個例子中做的事情可能相當於* dependency injection *,但是沒有任何繼承關於第二個例子,也沒有繼承,但是你使用'bar'作爲一個'foo'的裝飾器,所以你可以做'this.foo.baz',這對裝飾器的實現來說是完全有效的。 – amenadiel 2015-04-04 16:26:10
我與@brianvaughn - 目前看起來很好,但它可能不會取決於根據實際需要,確實有更好的辦法 – vlaz 2015-04-04 16:26:18