javascript - Access property of an object from a nested object -



javascript - Access property of an object from a nested object -

let's have 2 constructors these:

function player(x, y) { this.x = x; this.y = y; this.hello = function() { console.log("hello, " + this.npc); // world npc property } } function world() { this.player = new player(0, 0); this.npc = "villager"; }

how can access npc property of world hello function in player?

this doesn't work, since world not prototype of player.

use call. when used, allow bind this context world called hello function in player.

class="snippet-code-js lang-js prettyprint-override">function player(x, y) { this.x = x; this.y = y; this.hello = function() { alert("hello, " + this.npc); // world npc property } } function world() { this.player = new player(0, 0); this.npc = "villager"; this.player.hello.call(this); } new world();

javascript oop

Comments

Popular posts from this blog

assembly - What is the addressing mode for ld, add, and rjmp instructions? -

vowpalwabbit - Interpreting Vowpal Wabbit results: Why are some lines appended by "h"? -

Is there a way to convert an HTML page styled with Bootstrap CSS into email-compatible html? -