我在javascript中編寫了一些類,併爲它們編寫了一些FunctionFactories。但我認爲我做了一些錯誤的事情。JavaScript中的「this」。引用工廠內的一個對象
我重命名了我的代碼的一些內容,以便您更好地理解它。
所以第一類是「根」類。這個班有孩子,我稍後再添加。
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];
};
}
現在的問題是。當我調試代碼並在根對象的「渲染」功能中設置斷點時。然後我可以看到,「這個」不是根,而是「基礎」對象。我不明白爲什麼它是這樣的,因爲「根」對象是這個函數的所有者,我的基地有一個自己的渲染功能,不直接在那裏調用。
因此,即使在該行「這一」
$.each(this.children,function(i,obj){
指「基地」對象。但「這」是「根」對象中......
希望你能幫助我:-)
編輯:
代碼讓它運行:
var test = new templateRoot();
test.addBase();
test.render();
編輯2:
「that」在「addBaseFactory」中指的是正確的「基礎」對象。
感謝您的回答。我試過你的解決方案並進行調試。問題在於「自我」在這裏反駁「窗口」。 – Laokoon 2013-02-15 10:06:46
這很奇怪。如果你使用'new'操作符調用'templateRoot()',那麼它的'this'將是被創建的新對象,因此'self'也將是該對象。如果你把它叫做'new'運算符,那麼'this'就是'window'(因此'self')。 – nnnnnn 2013-02-15 10:08:54
看到這是一個範圍問題,正在使用jQuery,不會'$ .proxy'解決所有提到的問題嗎? – 2013-02-15 10:12:58