sencha touch extend 单继承 和 mixins 实现多继承
继承可以达到代码的复用,利于维护和扩展。
sencha touch 中可以通过 extend 实现单继承,通过 mixins 实现多继承。
mixins 也很像实现接口,不过这些接口的方法已经实现了,不用自己写了。当然也可以复写基类的方法。
1 extend 继承
Ext.define('Person', {
constructor : function(name, age) {
this.name = name;
this.age = age;
},
walk : function() {
console.log('Person walk');
},
sleep : function() {
console.log('Person sleep');
}
});
Ext.define('Stu', {
extend : 'Person',
constructor : function(name, age, city) {
this.city = city;
// 调用父类构造器
// 因为底层调用的是 superMethod.apply , 所以参数以数组的形式传递
this.callParent([ name, age ]);
},
walk : function() {
console.log('Stu walk');
// 调用父类方法
this.callParent();
}
});
var s = Ext.create('Stu', 'leslie', 25, 'beijing');
console.log(s);
console.log(s.superclass);
console.log(s.name);
console.log(s.age);
console.log(s.city);
s.walk();
// s.superclass.walk();
s.sleep();
// Log 如下
// [Log] Object
// [Log] Object
// [Log] leslie
// [Log] 25
// [Log] beijing
// [Log] Stu walk
// [Log] Person walk
// [Log] Person sleep
2 mixins 多继承
Ext.define('Person', {
constructor : function(name, age) {
this.name = name;
this.age = age;
},
walk : function() {
console.log('Person walk');
},
sleep : function() {
console.log('Person sleep');
}
});
Ext.define('CanWalk', {
walk : function() {
console.log('can walk');
}
});
Ext.define('CanSing', {
sing : function() {
console.log('can sing');
}
});
Ext.define('Stu', {
extend : 'Person',
// 混入 CanWalk CanSing
mixins : [ 'CanWalk', 'CanSing' ],
// 也可为混入的类重新指定一个 key
// 默认为类名
// 这样当类名很长时:如 Enway.Leslie.CanWalk
// 不用这样引用 this.mixins['Enway.Leslie.CanWalk']
// 而是直接通过 this.mixins.canWalk 引用
// mixins : {
// canWalk : 'Enway.Leslie.CanWalk',
// canSing : 'Enway.Leslie.CanSing'
// },
constructor : function(name, age, city) {
this.city = city;
// 调用父类构造器
// 因为底层调用的是 superMethod.apply , 所以参数以数组的形式传递
this.callParent([ name, age ]);
},
walk : function() {
console.log('Stu walk');
// 调用父类方法
// this.callParent();
// 调用 CanWalk 的 walk 方法
this.mixins.CanWalk.walk();
// 调用 CanSing 的 sing 方法
this.mixins.CanSing.sing();
}
});
var s = Ext.create('Stu', 'leslie', 25, 'beijing');
console.log(s);
console.log(s.superclass);
console.log(s.name);
console.log(s.age);
console.log(s.city);
s.walk();
// s.superclass.walk();
s.sleep();
// Log 如下
// [Log] Object
// [Log] Object
// [Log] leslie
// [Log] 25
// [Log] beijing
// [Log] Stu walk
// [Log] can walk
// [Log] can sing
// [Log] Person sleep

浙公网安备 33010602011771号