我尝试创建一些像这样的对象:
Object_level_1 = Ext.extend ( Ext.util.Observable, {
PropA: null,
ProbB: null,
initComponent: function () {
Object_level_1.superclass.initComponent.call ();
},
setValue: function ( name, value ) { // it will come as 'PropA', 45
if ( this.hasOwnProperty ( name ) ) { // ' fixed base on dtan answer
// here is a problem 1
// how I can access correct property and set it up
// problem 2
// How I set up property value of right property by having variable name
this.fireEvent ( 'Update_on_level_1' );
}
}
}
Object_level_2 = Ext.extend ( Object_level_1, {
PropC: null,
ProbD: null,
initComponent: function () {
Object_level_1.superclass.initComponent.call ();
},
setValue: function ( name, value ) { // it will come as 'PropA', 45 or 'PropC', 100
Object_level_2.superclass.setValue ( name, value );
if ( this.hasOwnProperty ( name ) ) { // ' fixed base on dtan answer
// here is a problem 1 again
// how I can access correct property and set it up
// problem 2 again
// How I set up property value of right property by having variable name
this.fireEvent ( 'Update_on_level_2' );
}
}
}
有人知道解决方案吗?
答案 0 :(得分:2)
实际上,我发现了代码中的错误:
var
ClassName.superclass.methodName.call(this, arg1, arg2..)
。传递this
很重要,因为它会将被调用父方法的范围更改为当前对象的范围。 (您可以删除以下测试代码中的this
以查看不同的输出。)this.addEvents
中声明initComponent
。不确定是否有必要。以下是我的完整测试代码,其中包含输出:
var Obj1 = Ext.extend(Ext.util.Observable, {
propA: null,
propB: null,
initComponent: function() {
Obj1.superclass.initComponent.call(this);
},
setValue: function(name, value) {
if (name in this) { //Used dtan suggestion
this[name] = value;
console.log(this.propA, this.propB, this.propC, this.propD);
}else{
console.log(name+" is not in Obj1");
}
}
});
var Obj2 = Ext.extend(Obj1, {
propC: null,
propD: null,
initComponent: function() {
Obj2.superclass.initComponent.call(this);
},
setValue: function(name, value) {
Obj2.superclass.setValue.call(this, name, value);
}
});
var obj1 = new Obj1();
var obj2 = new Obj2();
obj1.setValue('propA', '1a'); //1a null undefined undefined
obj1.setValue('propB', '1b'); //1a 1b undefined undefined
obj2.setValue('propC', '2c'); //null null 2c null
obj2.setValue('propD', '2d'); //null null 2c 2d
obj1.setValue('propA', '1a'); //1a 1b undefined undefined
obj1.setValue('propB', '1b'); //1a 1b undefined undefined
obj1.setValue('propC', '1c'); //propC is not in Obj1
obj1.setValue('propD', '1d'); //propD is not in Obj1
obj2.setValue('propA', '2a'); //2a null 2c 2d
obj2.setValue('propB', '2b'); //2a 2b 2c 2d
obj2.setValue('propC', '2c'); //2a 2b 2c 2d
obj2.setValue('propD', '2d'); //2a 2b 2c 2d
尝试阅读ExtJS开发人员如何在src
文件夹中编写代码。您将看到Ext.extend
答案 1 :(得分:1)
尝试将此添加到您的if
声明中:
if ( name in this && this.hasOwnProperty(name) && this[name]) {
this.fireEvent ( 'Update_on_level_2' );
}
我认为更多的 this[name]
IE b / c我已经读过它自己有hasOwnProperty
的问题(这可能是IE6遗留的事情而不是对于较新的版本而言,这是一个很大的问题。)this[name]
是为了确保您的属性具有值。如果您不关心该值是false
还是null
,则可以取出该部分。此外,hasOwnProperty
方法会从prototype
中排除属性,这听起来就像您要的那样。
修改。 根据@Pointy的评论如下。