Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.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 - Fatal编程技术网

Javascript 如何访问对象中对象的父对象

Javascript 如何访问对象中对象的父对象,javascript,Javascript,大家好,假设我有这个: function example() { this.x = 0; this.y = 32; this.example2 = function() { } } 如何从example2中访问example.x/example.y 我这样问是因为我正在创建我的第一个“真正的”html5游戏,并且我计划在这个对象(玩家、敌人等)中有一个大的游戏对象和“模型”。除非有更好的方法……我已经完成了原型工作,但它们都在一个文件中,没有真正的结构化。如下:

大家好,假设我有这个:

function example()
{
   this.x = 0;
   this.y = 32;
   this.example2 = function()
   {

   }
}
如何从example2中访问example.x/example.y

我这样问是因为我正在创建我的第一个“真正的”html5游戏,并且我计划在这个对象(玩家、敌人等)中有一个大的游戏对象和“模型”。除非有更好的方法……我已经完成了原型工作,但它们都在一个文件中,没有真正的结构化。

如下:

function example()
{
   this.x = 0;
   this.y = 32;
   this.example2 = function()
   {
      console.log(this.x); // 0
   }
}

如果您仅反对计划有一个父项,则可以通过以下方式进行:

function example() {
   this.x = 0;
   this.y = 32;
   this.example2 = new function() {
       this.parent = undefined;
   }
   this.example2.parent = this;
}

var firstobject = new example();

// Saving a reference to example2.
var example2Object = firstobject.example2;

// Because of parent variable, you can access example2 parent without needing to have the parent object in a variable.
console.log(example2Object.parent.x);
console.log(example2Object.parent.y);

设置父对象的方法有很多种,这只是一个示例。

如果您希望方法在单独使用时仍引用其原始对象,则需要一个闭包:

function example()
{
   this.x = 0;
   this.y = 32;

   this.example2 = proxy(this, function() {
       console.log(this.x);
   });
}

var x = new example(),
fn = x.example2; // isolate method

fn(); // this will still work
它使用此辅助函数将函数绑定到对象:

// helper function to bind fn to ctx (context)
function proxy(ctx, fn)
{
    return function() {
        return fn.apply(ctx, arguments);
    }
}

你不能。这经常被问到。现在,让我们寻找另一个问题来结束这个问题,作为重复。哦,好吧,这足够快了,谢谢,我想我会找到其他问题。这是一个吗@JorgeFuentesGonzález编辑是在恩典中进行的period@meagar-答案似乎都是针对当前的问题。
var\u这是完全多余的。只需在
example2
中使用
this.x
this.y
。这样,如果他只有example2的引用,他就无法访问父对象。不,这不是多余的。如果他只引用了example2,那么我的解决方案也能起作用。如果该对象被设置为bigObject.ex=new example(),那么这段代码就可以很好地工作了。。。