【发布时间】:2014-12-23 19:47:28
【问题描述】:
当我希望返回的对象中的成员具有父作用域中定义的变量的正确值时,我遇到了一个问题。但是,这个成员的值永远不会改变,我必须创建一个 getter 方法来检索正确的值。举个简单的例子,下面是图的邻接矩阵表示的子集:
function AdjacencyMatrix() {
// Here is the set of Vertices
var V = [1, 2, 3];
// Here's some functionality that will remove a vertex at some point,
// right now we're just concerned with updating what V is equal to
function removeVertex(v) {
V.push(4);
V = [];
console.log(V);
}
// A "getter" method for the list of vertices
function getVertices() {
return V;
}
// Ran when the Adjacency Matrix is initialized
console.log(V);
return Object.freeze({
// Member that holds a reference to V
vertices: V,
// Methods that will be used later
removeVertex: removeVertex,
getVertices: getVertices
});
}
// Initially logs [1, 2, 3], which is expected
var M = AdjacencyMatrix();
// Logs [], which is expected
M.removeVertex();
// Logs [1, 2, 3, 4], which is unexpected.
// Instead, it should log []
console.log(M.vertices);
// Logs [], which is expected
console.log(M.getVertices());
返回对象中的vertices 成员不应该始终保持对变量V 指向的内容的引用吗?相反,在此示例中,访问M 上的vertices 成员会维护对最初分配给变量V 的数组的引用,并忽略变量V 的任何重新分配。
或者,当将vertices 成员分配给V 时,它是否持有对V 值的引用,而不是变量所具有的任何值?
对不起,如果这个问题的措辞难以理解,我已尽力陈述我的期望和结果。
【问题讨论】:
标签: javascript closures