Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/451.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 在JS中,数组的元素能否知道谁是该数组的所有者?_Javascript_Arrays_Oop_Function_Object - Fatal编程技术网

Javascript 在JS中,数组的元素能否知道谁是该数组的所有者?

Javascript 在JS中,数组的元素能否知道谁是该数组的所有者?,javascript,arrays,oop,function,object,Javascript,Arrays,Oop,Function,Object,这可能看起来有点奇怪,但让我详细说明一下。。。我有一个对象的实例(在本例中z是Bla的实例),它有一个其他对象(Bla2)的列表,类似这样: Bla = function() { this.array = [new Bla2(), new Bla2(), new Bla2()]; this.x = 4; } Bla2 = function() { this.y = MYOWNER.x; //in this case, z is the owner } z = new

这可能看起来有点奇怪,但让我详细说明一下。。。我有一个对象的实例(在本例中z是Bla的实例),它有一个其他对象(Bla2)的列表,类似这样:

Bla = function()
{
    this.array = [new Bla2(), new Bla2(), new Bla2()];
    this.x = 4;
}

Bla2 = function()
{
    this.y = MYOWNER.x; //in this case, z is the owner
}

z = new Bla();

默认情况下,没有元素不知道它们属于哪个数组。主要是因为一个元素很容易包含在多个数组中。考虑下面的

var x = new Bla2();
var array1 = [x];
var array2 = [x];
在这种情况下,
x
位于2个数组中,因此具有单个所有者属性本质上是不正确的

但是,如果特定情况允许,可以手动创建此关系。考虑下面的

this.array = [new Bla2(), new Bla2(), new Bla2()];
for (var i = 0; i < this.array.length; i++) {
  this.array[i].owner = this.array;
}
this.array=[new Bla2(),new Bla2(),new Bla2()];
for(var i=0;i
如何定义“所有者”?数组可以被任何数量的其他对象所持有的变量引用。谢谢你,这是一个非常好的解释!我会尽快(7分钟)接受你的回答。我想他是在寻找数组项引用拥有数组的对象,而不是数组的引用。如果是这样的话,一个更好的选择可能是在构造函数参数中传递引用,例如,
[新Bla2(这个)、新Bla2(这个)、新Bla2(这个)]
。是的,这是真的,天哪,我忘了我需要什么了。。。无论如何,这是个好答案。