这是来自Why is my prototype function not returning the property of the instance?的问题的跟进


  $ .getJSON(myjson,function(data){


        var json = data;
        for (i in json) {
            juuvies[i] = new Juuvy(i,json[i], font, keyfontsize, valfontsize, orbcol, orbkeycol, orbvalcol, paper);
            juuvies[i].juuv_it();
            var mykey = juuvies[i].init_nodes();
                            juuvies[i].orb.node.onmouseover = function() { console.log(mykey);};
        }
    });


还有我的init_nodes函数,


  Juuvy.prototype.init_nodes = function(){
          返回this.key;
      }


此时,我仅获得循环中的最后一个键,而不是每次都获得唯一的传递。有没有办法可以保留事件处理程序的分配?

最佳答案

您需要添加一个闭合

var json = data;
for (i in json) {
    juuvies[i] = new Juuvy(i,json[i], font, keyfontsize, valfontsize, orbcol, orbkeycol, orbvalcol, paper);
    juuvies[i].juuv_it();
    var mykey = juuvies[i].init_nodes();
    (function(i, mykey){
        juuvies[i].orb.node.onmouseover = function() {
            console.log(mykey);};
        };
    })(i, mykey);
});

10-08 12:29