Javascript钻石继承结构

前端之家收集整理的这篇文章主要介绍了Javascript钻石继承结构前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用节点但在JavaScript中寻找钻石继承的方法

  1. var util = require('util');
  2. function Base(example_value) {
  3. console.log(example_value);
  4. this.example_property = example_value;
  5. this.example_method = function() { ... };
  6. }
  7. function Foo(settings) {
  8. var f = settings.f;
  9. Base.call(x);
  10. this.settings = settings;
  11. }
  12. util.inherits(Foo,Base);
  13. function Bar(settings) {
  14. var b = settings.b;
  15. Base.call(b);
  16. this.settings = settings;
  17. }
  18. util.inherits(Bar,Base);
  19. var foo = new Foo({f: 'bar'});
  20. // 'bar' gets printed and I can call methods from Base..
  21. foo.example_method();
  22. var bar = new Bar({b: 'foo'});
  23. // 'foo' gets printed and I can call methods from Base..
  24. bar.example_method();

这里没有问题..但是我需要在另一个包含对象的Foo和Bar(和Base)中创建所有可用的东西:

  1. function Top(settings) {
  2. Foo.call(this,settings);
  3. Bar.call(this,settings);
  4. }
  5. util.inherits(Top,Foo);
  6. util.inhertis(Top,Bar);
  7. var top = new Top({some: 'value'});

“价值”被打印两次,这不是我追求的.像这样做继承可能不是最好的方法,所以寻找替代/建议来处理这种钻石形状结构.

附:没有包含原始代码,但修改后希望简化 – 我已经手工完成了这个,不要认为有任何错误,但我想要解决的问题应该在那里.

最佳答案
你能用代表团吗?

  1. function Top(settings) {
  2. this.foo = new Foo(settings);
  3. this.bar = new Bar(settings);
  4. }
  5. Top.prototype.conflictingMethod = function() {
  6. // use either this.foo or this.bar
  7. }
  8. Top.prototype.anotherMethod = function() {
  9. return this.foo.anotherMethod();
  10. }

您也可以使用mixins,但需要将它添加到您的类系统中. Ext-JS支持mixins http://www.sencha.com/learn/sencha-class-system

  1. // My/sample/CanSing.js
  2. Ext.define('My.sample.CanSing',{
  3. sing: function(songName) {
  4. alert("I'm singing " + songName);
  5. }
  6. });
  7. // My/sample/CanPlayGuitar.js
  8. Ext.define('My.sample.CanPlayGuitar',{
  9. playGuitar: function() {
  10. alert("I'm playing guitar");
  11. }
  12. });
  13. // My/sample/CanComposeSongs.js
  14. Ext.define('My.sample.CanComposeSongs',{
  15. composeSongs: function() {
  16. alert("I'm composing songs");
  17. return this;
  18. }
  19. });
  20. // My/sample/CoolGuy.js
  21. Ext.define('My.sample.CoolGuy',{
  22. extend: 'My.sample.Person',mixins: {
  23. canSing: 'My.sample.CanSing',canPlayGuitar: 'My.sample.CanPlayGuitar'
  24. }
  25. });
  26. // My/sample/Musician.js
  27. Ext.define('My.sample.Musician',canPlayGuitar: 'My.sample.CanPlayGuitar',canComposeSongs: 'My.sample.CanComposeSongs'
  28. }
  29. });
  30. // app.js
  31. var nicolas = new My.sample.CoolGuy("Nicolas");
  32. nicolas.sing("November Rain"); // alerts "I'm singing November Rain"

猜你在找的JavaScript相关文章