4

Let's say we have two constructors like 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 i access the npc property of World from the hello function in Player?

this doesn't work, since World is not a prototype of Player.

1
  • It seems like you'd want to tell hello who it's greeting. Pass it in as a param. Commented Nov 11, 2014 at 19:34

4 Answers 4

2

Use call. When used, it will allow you to bind the this context from 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();

Sign up to request clarification or add additional context in comments.

2 Comments

I like this, but what if i want to call the function in a second time? I can't make it work apart from the moment i initialize World.
@Cuz - You would use world.player.hello.call(world). Or you could internalize the hello function call to world since it doesn't have much to do with player. You could have hello expect to take a world object. You could have World inherit the prototype of player and implement its own hello function. There are many options, the one which requires the least amount of change is using call.
2

You have to instantiate the World function to make it an object as so:

var world = new World();
alert(world.npc);

2 Comments

Yes, that's the way i did, but i would like to know if there's a better way.
I don't see that in the example you provided. I think you did a great job separating the objects into different classes. I would not do it differently. This way will increase your code's usability.
1

Pass it as a parameter:

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

2 Comments

Why are you passing it to the Player constructor?
This assumes a lot about his desired architecture, but is a good solution.
0
var World = function () {
  this.npc = "villager";
  this.player = new Player(0, 0);  
  return {
    npc: this.npc,
    player: this.player
  };
}();

You can now access the npc from other contexts using World.npc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.