2

我用 javascript 编写了一些类,并为它们编写了一些 FunctionFactories。但我认为我做错了一些事情。

我重命名了我的代码中的一些内容,以便您更好地理解它。

所以第一类是“根”类。这个班有孩子,我稍后会添加。

function templateRoot(){
    this.id = "root";
    this.parent = null;
    this.children = [];

    this.editable = true; // bla

    this.render = function(){
        $.each(this.children,function(i,obj){
            this.children[i].render();
            var baseButtons = this.getBaseButtons();
            $('#'+this.id).append(baseButtons);
        });
    };
    this.addBase = addBaseFactory(this);
};

属性“addBase”获取一个由 addBaseFactory 提供的函数...

function addBaseFactory(that){
    return function(){
        var newBase = new base(that.children.length, that.id);
        that.children.push(newBase);
    };
}

...并且用于在“addBase”中生成对象的基类如下所示:

function base(count, parent){
    this.id = parent+"_base"+count;
    this.parent = parent;
    this.children = [];
    this.remove = function (){
        $('#'+this.id).remove();        
    };
    this.render = baseRenderFactory(this);
    this.addChild = addChildFactory(this);
    this.getBaseButtons = function(){
        var addAttributeButton = new $("<button>+ Attribute</button>").button();
        var addTextButton = new $("<button>+ Text</button>").button();
        return [addAttributeButton, addTextButton];
    };
}

现在的问题是。当我调试代码并在根对象的“渲染”函数中设置断点时。然后我可以看到,“this”不是根,而是“基础”对象。而且我不知道为什么会这样,因为“根”对象是这个函数的所有者,而我的基础有一个自己的渲染函数,它没有直接在那里调用。

所以即使是行中的“this”

$.each(this.children,function(i,obj){

指“基础”对象。但是“this”在“root”对象中......

希望你能帮我 :-)


编辑:

让它运行的代码:

var test = new templateRoot();
test.addBase();
test.render();

编辑2:

“addBaseFactory”中的“that”指的是正确的“base”对象。

4

2 回答 2

2

我发现你的解释很混乱,所以我可能误解了你想要做的事情,但我认为你在嵌套函数中期望与外部函数中的this对象相同。这不是JavaScript 的工作方式。嵌套函数与包含函数的继承不同——每个函数都有自己的对象,该对象根据函数的调用方式进行设置。thistemplateRoot()thisthisthis

这是一种可能的解决方案,它使用嵌套函数可以从其包含函数中看到变量的事实:

function templateRoot(){
    var self = this; // save a reference to this for use in nested functions
    this.id = "root";
    this.parent = null;
    this.children = [];

    this.editable = true; // bla

    this.render = function(){
        $.each(self.children,function(i,obj){
            self.children[i].render();
            var baseButtons = this.getBaseButtons();
            $('#'+self.id).append(baseButtons);
        });
    };
    this.addBase = addBaseFactory(this);
};

this可以在MDN中找到有关 JS 工作原理的详细说明。

于 2013-02-15T09:59:38.827 回答
0

这不会呈现它的childerens孩子,因为jquery会这样发送每个孩子吗?

this.render = function(){
    $.each(this.children,function(i,obj){
        this.children[i].render();
        var baseButtons = this.getBaseButtons();
        $('#'+this.id).append(baseButtons);
    });
};

顺便说一句,addBaseFactory 在什么范围内被调用?因为我认为基础中的“this”将指代那个范围。

于 2013-02-15T10:01:57.433 回答