JavaScript中的“this”。引用工厂内的对象

时间:2013-02-15 09:50:16

标签: javascript oop reference this

我在javascript中编写了一些类,并为他们编写了一些FunctionFactories。但我认为我做错了。

我重命名了一些代码,你可以更好地理解它。

所以第一个类是“root”类。这个班有孩子,我后来加了。

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];
    };
}

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

所以即使行中的“这个”

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

指“基础”对象。但是“这个”在“根”对象里面......

希望你能帮助我: - )


修改

让它运行的代码:

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

编辑2:

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

2 个答案:

答案 0 :(得分:2)

我发现你的解释非常令人困惑,所以我可能误解了你想要做的事情,但我认为你希望嵌套函数中的this与外部this函数中的templateRoot()。这不是this在JavaScript中的工作方式。嵌套函数不会继承与包含函数相同的this - 每个函数都有自己的this对象,该对象根据函数的调用方式设置。

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

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如何在JS工作的详细说明,请访问MDN

答案 1 :(得分:0)

这会不会给孩子们带来孩子,因为jquery会把每个孩子送到这个孩子身上吗?

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

btw在什么范围内调用addBaseFactory?因为我认为基础中的“这个”,将参考该范围。