Javascript钻石继承结构

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

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

var util = require('util');

function Base(example_value) {
  console.log(example_value);
  this.example_property = example_value;
  this.example_method = function() { ... };
}

function Foo(settings) {
  var f = settings.f;
  Base.call(x);
  this.settings = settings;
}

util.inherits(Foo,Base);

function Bar(settings) {
  var b = settings.b;
  Base.call(b);
  this.settings = settings;
}

util.inherits(Bar,Base);

var foo = new Foo({f: 'bar'});
// 'bar' gets printed and I can call methods from Base..
foo.example_method();
var bar = new Bar({b: 'foo'});
// 'foo' gets printed and I can call methods from Base..
bar.example_method();

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

function Top(settings) {
  Foo.call(this,settings);
  Bar.call(this,settings);
}

util.inherits(Top,Foo);
util.inhertis(Top,Bar);

var top = new Top({some: 'value'});

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

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

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

function Top(settings) {
  this.foo = new Foo(settings);
  this.bar = new Bar(settings);
}

Top.prototype.conflictingMethod = function() {
   // use either this.foo or this.bar
}
Top.prototype.anotherMethod = function() {
   return this.foo.anotherMethod();
}

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

// My/sample/CanSing.js
Ext.define('My.sample.CanSing',{
    sing: function(songName) {
        alert("I'm singing " + songName);
    }
});

// My/sample/CanPlayGuitar.js
Ext.define('My.sample.CanPlayGuitar',{
    playGuitar: function() {
        alert("I'm playing guitar");
    }
});

// My/sample/CanComposeSongs.js
Ext.define('My.sample.CanComposeSongs',{
    composeSongs: function() {
        alert("I'm composing songs");

        return this;
    }
});

// My/sample/CoolGuy.js
Ext.define('My.sample.CoolGuy',{
    extend: 'My.sample.Person',mixins: {
        canSing: 'My.sample.CanSing',canPlayGuitar: 'My.sample.CanPlayGuitar'
    }
});

// My/sample/Musician.js
Ext.define('My.sample.Musician',canPlayGuitar: 'My.sample.CanPlayGuitar',canComposeSongs: 'My.sample.CanComposeSongs'
    }
});

// app.js
var nicolas = new My.sample.CoolGuy("Nicolas");
nicolas.sing("November Rain"); // alerts "I'm singing November Rain"
原文链接:https://www.f2er.com/js/429750.html

猜你在找的JavaScript相关文章