Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从嵌套对象访问对象的属性_Javascript_Oop - Fatal编程技术网

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

Javascript 从嵌套对象访问对象的属性,javascript,oop,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"; } 如何从

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

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属性


这不起作用,因为世界不是玩家的原型。

将其作为参数传递:

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);  
}
您现在可以使用
World.npc

使用从其他上下文访问
npc
。使用时,它将允许您从World将
上下文绑定到Player中被调用的hello函数

功能播放器(x,y){
这个.x=x;
这个。y=y;
this.hello=function(){
警报(“你好,”+this.npc);//世界npc属性
}
}
函数世界(){
this.player=新玩家(0,0);
this.npc=“村民”;
这个。玩家。你好。打电话(这个);
}

新世界()您必须实例化
World
函数,使其成为对象:

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

好像你想告诉我打招呼的是谁。将其作为参数传递。为什么要将其传递给
Player
构造函数?这假设了他所需的很多架构,但这是一个很好的解决方案。是的,我就是这样做的,但我想知道是否有更好的方法。在您提供的示例中,我没有看到这一点。我认为您在将对象划分为不同类方面做得很好。我不会改变的。这样可以提高代码的可用性。我喜欢这样,但是如果我想再次调用这个函数呢?除非我初始化World,否则我无法使它工作。@Cuz-您将使用
World.player.hello.call(World)
。或者您可以将hello函数调用内部化为world,因为它与player没有太多关系。你可以期望得到一个世界物体。您可以让World继承player的原型并实现其自己的hello函数。有很多选择,其中需要最少更改的是使用
call
var world = new World();
alert(world.npc);