簡體   English   中英

從嵌套對象訪問對象的屬性

[英]Access property of an object from a nested object

假設我們有兩個這樣的構造函數:

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不是Player的原型。

使用call 使用時,它允許您this上下文從World綁定到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(); 

您必須實例化World函數以使其成為對象:

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

將其作為參數傳遞:

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);  
}
var World = function () {
  this.npc = "villager";
  this.player = new Player(0, 0);  
  return {
    npc: this.npc,
    player: this.player
  };
}();

您現在可以使用World.npc從其他上下文訪問npc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM