链接变量

时间:2013-02-13 02:19:43

标签: javascript node.js

这是我的代码的简单摘要:

var list = {
    "group":{
        "subgroup1":[{"name1":"Jimmy","name2":"Bob"}],
        "subgroup2":[{"name1":"Sarah","name2":"Nick"},{"name1":"Kevin","name2":"George"}]
    }
}
function group(group,name){
    var linktothegroup;

    //Note: In my actual code it will attempt to join a group before creating one this just creates a new one


    //group: Specifies which subgroup to join (my actual code will check if it's valid this is just a simpler version
    //name: the users name

    list["group"][group].push({"name1":name,"name2":""});
    linktothegroup = someway to link that group I just added; //I figured I could find the array slot and specify but that will change if a group is deleted

    this.leavegroup = function(){
        //leaves the group
        //uses the linktothegroup var to be removed from the group
    }
    this.changename = function(name){
        linktothegroup.name1 = name;
        return true;
    }
}
var cubscouts = new group("subgroup1","Billy");
cubscouts.changename("Fred");

我只想编辑“subgroupX”字段中的值(基本上是对于changename函数),但是有些组一直在离开和加入,所以我不能在变量中指定数组槽。

所以基本上有一种方法可以编辑一个变量并使用它来改变另一个变量吗?

2 个答案:

答案 0 :(得分:2)

这样的事情怎么样?:

var groups = {

  joinGroup: function(groupName, memberName) {
    if(!this[groupName]) {  // create the group if it doesn't exist
      this[groupName] = []  // each group is just an array of names
    }
    var group = this[groupName]
    group.push(memberName)

    // returns an object allowing for the member's name to be changed later
    return {
      // this function becomes a closure, so the group and memberName variables
      // retain their values from the enclosing scope
      changeName: function(newMemberName) {
        group.splice(group.indexOf(memberName), 1, newMemberName)
      }
    }
  }
}

允许这种用法:

myCubscoutMembership = groups.joinGroup('cubscouts', 'Billy')
myCubscoutMembership.changeName('Bob')

谜题的关键部分(如果我理解你的问题)是changeName函数在groupmemberName变量周围作为closure返回 - 因此,即使稍后调用changeName,也会记住正确的组和旧名称。

为了保持答案的集中,我省略了leaveGroup()方法,但可以将其作为另一个函数添加到返回的对象中。我也没有解决如果整个组被删除会发生什么,但这取决于你的应用程序有什么意义。

原始样本的几个简化:

  1. 我将顶级list var弄平,似乎只包含一个group
  2. 我将每个组简化为名称数组而不是哈希,即 ['billy', 'bob']代替{ name1: 'billy', name2: 'bob' }
  3. 希望其中一些有用。

答案 1 :(得分:1)

您可以将对象存储在函数中引用的变量中。

function group(group,name){
    //other work here
    var linktothegroup = {"name1":name,"name2":""};
    list["group"][group].push(linktothegroup);

    this.leavegroup = function(){
        var groups = list["group"][group];
        for(var i = 0; i < groups.length; i++) {
            if(groups[i] === linktothegroup) {
                groups.splice(i, 1);
                break;
            }
        }
    }
    this.changename = function(name){
        linktothegroup.name1 = name;
        return true;
    }
}