2010-06-04 110 views
4

我已经建立了MooTools的一类,并延长了两次,这样是有祖父母,父母和子女的关系:如何在Mootools中获得this.grandparent()功能?

var SomeClass1 = new Class({ 
    initialize: function() { 
    // Code 
    }, 
    doSomething: function() { 
    // Code 
    } 
}); 

var SomeClass2 = new Class({ 
    Extends: SomeClass1, 
    initialize: function() { 
    this.parent(); 
    }, 
    doSomething: function() { 
    this.parent(); 
    // Some code I don't want to run from Class3 
    } 
}); 

var SomeClass3 = new Class({ 
    Extends: SomeClass2, 
    initialize: function() { 
    this.parent(); 
    }, 
    doSomething: function() { 
    this.grandParent(); 
    } 
}); 

Class3,孩子,我需要从Class1调用doSomething()法,祖父母,而不执行Class2#doSomething()父母的任何代码。

我需要的是grandParent()方法来补充Mootools parent(),但它似乎不存在。

在Mootools或纯JavaScript中完成此操作的最佳方法是什么?谢谢。

UPDATE:

我应该提到:我意识到,不良设计已经离开我,要问在首位这个问题。一个mixin将是理想的,但我继承了代码,并没有时间进行重构。

回答

1

这个,如果你添加SomeClass1作为一个混合和SomeClass3去除doSomething本地定义,然后调用实例上的方法doSomething将调用SomeClass1.doSomething();直接可能不会为你工作,但...。

如果SomeClass3上的doSomething需要运行本地/独立代码,但您可以解决此问题,这可能不太实际。

http://www.jsfiddle.net/29MGa/1/

必须有获得从N级继承链的根的一种方式,但我不能帮助你。你应该去mootools邮件列表并发布这个信息,希望核心团队的某些人能够回答(如ryan florence,aaron newton,christoph pojer等)。另一个很好的来源是irc.freenode.net上的mootools irc频道#mootools。

祝你好运,请用你的发现来更新,因为你永远不知道什么时候可能需要这个。从IRC

更新:

<akaIDIOT> SomeClass1.prototype.doSomething.apply(this[, ...]);

<akaIDIOT> not as clean as .parent(), but Moo doesn't give you a grandparent :)

也混入得到了大拇指各种各样的:

<rpflo> d_mitar: I've often found that if I'm trying to do that it might make more sense for class 2 or 3 to be a mixin

<rpflo> but yeah, akaIDIOT's should work

+0

感谢您的mixin建议。这对我很有用,但是,我正在处理大量现有的代码,这些代码有点不尽人意,重构需要的时间比我目前愿意付出的时间要多。 我一定会更新此线程与解决方案,如果我找到一个。 – 2010-06-07 06:48:49

+0

酷,我问irc有关它,并得到了一些想法,回答更新 – 2010-06-07 14:18:56

0

我没有手头MooTools的测试,但...

你试过

(this.parent()).parent(); 

+0

这将仍然导致父类的方法来运行。 – 2010-06-04 22:00:26

0

你可以把它叫做祖父母班吗?

SomeClass1.doSomething.apply(this,arguments); 

或甚至:

SomeClass1.prototype.doSomething.apply(this, arguments); 

我不是100%肯定MooTools的类是如何工作的,但这些建议应该工作。

另外,如果SomeClass2中的doSomething()功能不在SomeClass3中继承,​​那么SomeClass2为什么是父类?您应该能够使另一个类成为包含SomeClass2和SomeClass3所需功能的父类,然后允许每个类以其自己的方式覆盖doSomething()方法。

2

正如前面提到的,我敢打赌,在这里使用mixin更有意义,但在这里你会走。

http://jsfiddle.net/rpflorence/24XJN/

var GrandParent = new Class({ 
    initialize: function(){ 
     console.log('init:GrandParent'); 
    }, 
    talk: function(){ 
     console.log('talk:GrandParent'); 
    } 
}); 

var Parent = new Class({ 
    Extends: GrandParent, 
    initialize: function(){ 
     this.parent(); 
     console.log('init:Parent'); 
    }, 
    talk: function(){ 
     console.log('talk:Parent'); 
    } 
}); 

var Child = new Class({ 
    Extends: Parent, 
    initialize: function(){ 
     this.parent(); 
     console.log('init:Child'); 
    }, 
    talk: function(){ 
     GrandParent.prototype.talk.apply(this); 
     console.log('talk:Child'); 
    } 
});