Javascript nested function attribute inheritance -



Javascript nested function attribute inheritance -

im trying utilize attribute of function in nested function don't know how, without passing parent function.

example:

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

so far tryed this:

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

is there pattern accomplish this? since workaround mess

edit:

since of wanted more reallife 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, // need access games world attribute y: 0 } }

but isn't attribute of game class need in player class..

updated answer

you may want read encapsulation. given updated example, reasonable pass reference game each of player instances so:

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, // need access games world attribute y: 0 } } player.prototype.anotherfunction = function() { console.log(this.game); // has access `this.game` }

as vld@ says, there improve ways accomplish you're trying in illustration suspect more general question.

original answer

one way accomplish you're trying inheritance, so:

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"

javascript function class inheritance

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -