ExtJs继承行为 [英] ExtJs inheritance behaviour
问题描述
让我们声明一个类:
Ext.define('baseClass',{
a:null,
ar:[],
add:function(v){
this.ar.push(v);
},
sayAr:function ){
console.log(this.ar);
},
setA:function(v){
this.a = v;
},
sayA:function(){
console.log(this.a);
}
});
现在我创建两个对象
var a = Ext.create('baseClass');
var b = Ext.create('baseClass');
测试属性
a.setA(1);
b.setA(2);
a.sayA();
b.sayA();
此输出
code> 1
2
一切都可以,但
a.add(1);
b.add(2);
a.sayAr();
b.sayAr();
我们得到
code> [1,2]
[1,2]
不明白为什么它为两个对象使用单独的a属性,但是使用一个ar数组。
ar不声明为静态!
我根本没有得到它。
当你把某些东西放在课堂宣言中,这意味着被推送到对象原型(阅读:它在所有实例中共享)。字符串/数字/布尔不是一个问题,但是对于对象和数组,您将看到这种行为会生效。
如果你想要一个数组/ object每个实例,那么你需要在实例中显式地添加它:
Ext.define('baseClass',{
a:null,
构造函数:function(){
this.ar = [];
}
add:function(v) {
this.ar.push(v);
},
sayAr:function(){
console.log(this.ar);
},
setA:function(v){
this.a = v;
},
sayA:function(){
console.log(this。 a);
}
});
Can someone please explain this behavior to me. Lets declare a class:
Ext.define('baseClass',{
a:null,
ar:[],
add:function(v) {
this.ar.push(v);
},
sayAr:function() {
console.log(this.ar);
},
setA:function(v) {
this.a= v;
},
sayA:function() {
console.log(this.a);
}
});
Now I create two objects
var a = Ext.create('baseClass');
var b = Ext.create('baseClass');
Test the property
a.setA(1);
b.setA(2);
a.sayA();
b.sayA();
This outputs
1
2
Everything is OK, but
a.add(1);
b.add(2);
a.sayAr();
b.sayAr();
We get
[1,2]
[1,2]
This I don't understand. Why does it use separate "a" properties but one "ar" array for both objects. "ar" is not declared as static! I don't get it at all.
When you put something in the class declaration, it means it gets pushed onto the object prototype (read: it gets shared across all instances). It's not really a problem for strings/numbers/bools, but for objects and arrays you'll see this behaviour come in to effect.
If you want to have an array/object per instance, then you need to explicitly add it in the instance:
Ext.define('baseClass',{
a:null,
constructor: function(){
this.ar = [];
}
add:function(v) {
this.ar.push(v);
},
sayAr:function() {
console.log(this.ar);
},
setA:function(v) {
this.a= v;
},
sayA:function() {
console.log(this.a);
}
});
这篇关于ExtJs继承行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!