Javascript对象混淆
我把自己搞糊涂了。我的设想如下Javascript对象混淆,javascript,javascript-events,Javascript,Javascript Events,我把自己搞糊涂了。我的设想如下 function DesignPad() { function EditBar() { ... this.removeHandler = function() { **// how do I call Dragger.removeAsset** } } function Dragger(){ ... this.removeAsset = function() {} } this.in
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),但我的事件处理程序似乎有各种各样的混乱。对这些东西有什么建议,好的阅读材料等吗
谢谢 在我看来,您应该重构代码以使其更简单
我认为您的问题来自这样一个事实:嵌套函数是私有的,因此您不能从外部访问它 Dragger实例是设计板对象的“属性”吗?如果是这样,您可以将对该对象的引用传递到removeHandler()方法。我发现这是对JavaScript最好的介绍。特别是Yahoo的视频,比如:在那里你可以了解对象是如何在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();
但正如其他人所注意到的,您可以重构一些东西:)。尝试以下方法:
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');
被6分钟击败,还有一个更好的解决方案:)注意你的意思是警惕(不是打印)。顺便说一下,这是一个绝妙的解决方案。只是想澄清一下,当您输入EditBar函数时,将创建一个闭包。闭包会记住周围发生的事情,因此它也会记住“那个”变量。即使你将函数分配给某个外部事件,闭包仍然存在,就是这样。谢谢肯定也会仔细看看Crockford的网站。再次感谢。@Michał这是我从Crockford中学到的一个简洁的解决方案-他是出色的JavaScripter:)@MichTaiwan打印是因为我使用Rhino进行了测试:)我认为你应该使用“var super=”而不仅仅是“super=”:)