私有变量在类的多个实例之间共享

时间:2014-06-14 14:51:56

标签: javascript jquery inheritance prototypal-inheritance draw2d-js

我在JavaScript函数中使用私有变量时遇到一个小问题。该软件依赖于draw2d,一个javascript渲染库。该库迫使您使用John Resig的Class.js实现,它允许简单的Java类继承,以及我认为是问题的根源。

//= require block/XBlock.js
console.log("sblock loaded.");
xmicro.block.SimpleBlock = xmicro.block.XBlock.extend({
    NAME: "xmicro.block.SimpleBlock",

    init: function(path, width, height,input,output,contextMenua){
        this._super(path,width,height,input,output,contextMenua);
        image = path;
        this.contextMenu = contextMenua;
        xmicro.istn.BlockAttributeStore[this.id] = new xmicro.block.BlockAttributeStore();
    },
    getImage: function () {
        return this.image;
    },

    onContextMenu: function (x, y) {
        supaId = this.id;
        that = this;
        var buildFunc = function(){
            var args = Array.prototype.slice.call(arguments);
            args.push(supaId);
            return that.contextMenu.build.apply(null, args);    
        };
        if(this.contextMenu !== undefined){
            $.contextMenu({
                trigger: "right",
                selector: this.contextMenu.selector,
                build: buildFunc
            });
        }
    },

    getPersistentAttributes: function () {
        var memento = this._super();

        return memento;
    }
});

顶部的注释会进行一些自动连接,但问题的焦点是onContextMenu功能。我有一个需要调用的闭包,以便从属性对象构建一个jQuery上下文菜单。该属性对象中的一件事是一个名为build的方法,为此我使用buildFunc来拦截调用并附加调用它的图形的id。

问题在于,如果我声明var supaId = this.id,当我制作更多类型的数字时,他们会开始分享supaId,并开始交叉污染变量。另一个问题是,如果我像下面的supaId = this.id一样使用它,那么它可以工作,但是可以将supaId放在全局范围内。这些都不是我的好选择,我想了解如何解决它。

感谢任何帮助!

0 个答案:

没有答案