Javascript对象混淆

cngwdvgl  于 2022-12-28  发布在  Java
关注(0)|答案(4)|浏览(117)

我把自己弄糊涂了,我的情况如下:

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),但是我的事件处理程序似乎把所有的东西都搞混了。有什么建议,好的阅读材料,等等吗?

6rqinv9w

6rqinv9w1#

我发现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();

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

nxowjjhe

nxowjjhe2#

对我来说,它只是看起来像你应该重构代码,使其更简单。
我认为你的问题来自于嵌套函数是私有的,所以你不能从外部访问它。

toe95027

toe950273#

Dragger的示例是DesignPad对象的“属性”吗?如果是,可以将对该对象的引用传递到removeHandler()方法中。

xa9qqrwz

xa9qqrwz4#

试试这个:

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

相关问题