Access to an object object from a nested object

Let's say we have two such constructors:

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 I access the npc property for World from the hello function in Player?

this one does not work since World is not a prototype Player.

+4
source share
4 answers

Use call. When used, it will allow you to bind the context thisfrom World to the called hello function in Player.

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();
Run codeHide result
+2
source

You need to instantiate a function Worldto make it an object as follows:

var world = new World();
alert(world.npc);
+2
source

:

function Player(x, y) {
  this.x = x;
  this.y = y;
  this.hello = function(npc) {
    console.log("Hello, " + npc); // World npc property
  }
}

function World() {
  this.npc = "villager";
  this.player = new Player(0, 0);
  this.player.hello(this.npc);  
}
+1
var World = function () {
  this.npc = "villager";
  this.player = new Player(0, 0);  
  return {
    npc: this.npc,
    player: this.player
  };
}();

npc , World.npc.

0

All Articles