Javascript对象混淆

时间:2009-05-12 18:52:28

标签: javascript javascript-events

我在这里很好地混淆了自己。我的方案如下。

function DesignPad() {  
 function EditBar() {  
  ...  
  this.removeHandler = function() {  
    **// how do I call Dragger.removeAsset**  
  }  
 }  
 function Dragger(){  
  ...  
  this.removeAsset = function() {}  
 }  
 this.init = function() {  
  this.editBar = new EditBar();  
  this.dragger = new Dragger();  
 }  
}  

var dp = new DesignPad();  
...

我似乎无法调用Dragger.RemoveAsset。我理解为什么,我的问题是如何称呼它?

我正在尝试保持相似的东西(例如Dragger / EditBar),但我似乎在我的事件处理程序中混淆了各种各样的东西。关于这个东西的任何建议,好的阅读材料等?

感谢。

4 个答案:

答案 0 :(得分:3)

我发现Douglas Crockford's Javascript是JavaScript的最佳介绍。特别是雅虎的视频,例如:The JavaScript Programming Language,您可以在其中了解如何在JS中创建和继承对象。

解决问题的方法是:

function DesignPad() {  
  var that = this;
 function EditBar() {  
  this.removeHandler = function() {  
    print("RemoveHandler");
    that.dragger.removeAsset();
  }  
 }  
 function Dragger() {  
  this.removeAsset = function() {
    print("RemoveAsset");
  }  
 }  
 this.init = function() {  
  this.editBar = new EditBar();  
  this.dragger = new Dragger();  
 }
}  

var dp = new DesignPad();
dp.init();
dp.editBar.removeHandler();

但正如其他人注意到你可以重构一些事情:)。

答案 1 :(得分:0)

对我而言,看起来您应该重构该代码以使其更简单。

我认为您的问题来自于嵌套函数是私有的,因此您无法从外部访问它。

答案 2 :(得分:0)

Dragger的实例是DesignPad对象的'属性'吗?如果是这样,您可以将对该对象的引用传递给removeHandler()方法。

答案 3 :(得分:0)

试试这个:

function DesignPad() {  

 function EditBar(s) {  
  super = s;
  this.removeHandler = function() {
    alert('call 1'); 
    super.dragger.removeAsset();  
  }  
 } 


 function Dragger(s){
  super = s;  
  this.removeAsset = function() {
      alert('call 2'); 
    }  
 }  

 this.init = function() {  
  this.editBar = new EditBar(this);  
  this.dragger = new Dragger(this);  
 }  

}  

var dp = new DesignPad(); 
dp.init()
dp.editBar.removeHandler();
alert('end');
相关问题