English 中文(简体)
Javascript 对象混淆
原标题:
  • 时间:2009-05-12 18:52:28
  •  标签:

I ve confused myself nicely here. My scenario is as follows:

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),但在我的事件处理程序中好像出现了各种混淆。在这方面是否有任何建议、好的阅读材料等?

最佳回答

I found Douglas Crockford s Javascript to be the best introduction to JavaScript. Especialy videos for Yahoo, like: The JavaScript Programming Language where you can learn how exactly are objects created and inherited in 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();

但是正如其他人注意到的那样,您可以重构一些东西 :)。

问题回答

在我看来,你应该重构那段代码让它更简单。

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

拖放器的实例是否是DesignPad对象的属性?如果是,您可以将对该对象的引用传递到您的removeHandler()方法中。

Try this:

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 );




相关问题
热门标签