我用 javascript 编写了一些类,并为它们编写了一些 FunctionFactories。但我认为我做错了一些事情。
我重命名了代码中的一些内容,以便您可以更好地理解它。
所以第一个类是“root”类。这个类(class)有 child ,我稍后添加。
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”指的是正确的“基础”对象。
最佳答案
我发现你的解释非常困惑,所以我可能误解了你想要做的事情,但我认为你期望嵌套函数中的this
具有相同的效果对象作为外部 templateRoot()
函数中的 this
。这不是 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 找到。 .
关于javascript - JavaScript 中的 "this"。对工厂内对象的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14891992/