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

javascript - THREE.js reposition vertices for RingGeometry -

javascript - I need to update the text of a paragraph by inline edit -

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