2

我在 JavaScript 中有一个小问题。我想做以下事情:

var peter = {
  pet : spot
}

var spot = {
  owner : peter
}

上面的代码运行良好,但 peter.pet 将是未定义的。而 spot.owner 将被定义。有没有更好的方法然后做类似的事情:

var peter = {
  pet : 'spot'
}

var spot = {
  owner : peter
}

peter.pet = eval(peter.pet)

任何见解将不胜感激...

4

3 回答 3

5

由于对象是动态的,pet稍后添加:

var peter = {
    // anything else you want to set
};

var spot = {
    owner : peter
};

peter.pet = spot;

编辑 - 删除了向 peter 对象添加函数的错误尝试。要做到这一点,请参阅 Renan 的帖子。

于 2013-07-22T19:04:13.307 回答
3

创建点后设置参考:

var peter = {
  pet : undefined
}

var spot = {
  owner : peter
}

peter.pet = spot
于 2013-07-22T19:04:30.890 回答
2
var peter = {};
var spot = {owner: peter};
peter.pet = spot;

或者,您可以加强打字:

PetOwner = function () {};
PetOwner.prototype.pet = null;

Animal = function (owner) {
    this.owner = owner;
    this.owner.pet = this;
};
Animal.prototype.owner = null;

var peter = new PetOwner();
var spot = new Animal(peter);
于 2013-07-22T19:04:40.830 回答