2

我有一个 JavaScript 对象Team和一个Score代表点和其他一些功能的对象。我想知道在将分数存储在团队中的同时将团队存储在分数中是否安全。

var Score = function(team){
    this.team = team;
    this.points = 0;
    ...
}

var team = {
    name : 'Team 1',
}
team.score = new Score(team);

这样做的结果是,如果我 log team.score.team.score.team.score.team.score.team.score.points= 0。这对于我正在编程的内容来说是完美的,但是它是否代表一个危险的设置,可能会导致旧版浏览器崩溃或导致任何其他问题?它看起来就像一个无限循环,但 Chrome 似乎处理得很好。

有什么理由我不应该这样做吗?

4

2 回答 2

1

Good question by the way.

This is called circular referencing.

Meaning the you are creating the nested reference of the same object.

Garbage collection in browsers: The main function of the garbage collector in the browser is to free the memory if the memory occupied by the object is no longer in use. But in the case of circular reference

An object is said to reference another object if the former has an access to the latter (either implicitly or explicitly). For instance, a JavaScript object has a reference to its prototype (implicit reference) and to its properties values (explicit reference)

(Source MDN)


This is forcing the garbage collecting algorithm to prevent the object from being garbage collected, which in turn is a memory leak.

As per the MDN Mark and sweep algorithm is been improved in such circumstance of circular referencing which is intelligent enough to remove the object of this type.

Circular referencing was a problem in IE < 8 which caused the IE browsers to go hay wire on this. Read this link and this one


IBM link

This article sheds light on JavaScript circular referencing memory leak with example and clarity on the subject.


Final Verdict: Better to avoid circular referenced objects, only use when its highly needed at programmers discretion. As modern browsers today are quite efficiently built though but its not a good practice as a developer to write code that causes unwanted memory consumption and leaks.

于 2016-10-03T11:37:47.487 回答
-6
var Score = function(team,point){
    this.team = team;
    this.points = 0;
    ...
}

var team = {
    name : 'Team 1',
   point : 'point'
}
team.score = new Score(team);
team.score = new Score(point);

试试这个,也许它可以帮助你

于 2016-10-03T10:24:55.317 回答