从嵌套对象访问对象的属性

时间:2014-11-11 19:31:47

标签: javascript oop

我们假设我们有两个这样的构造函数:

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

如何从Player中的hello函数访问World的npc属性?

不起作用,因为World不是播放器的原型。

4 个答案:

答案 0 :(得分:2)

使用call。使用时,它允许您将来自World的this上下文绑定到Player中的被调用hello函数。

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

答案 1 :(得分:2)

您必须实例化World函数才能使其成为对象:

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

答案 2 :(得分:1)

将其作为参数传递:

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

答案 3 :(得分:0)

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

您现在可以使用npc从其他上下文访问World.npc