在ext项目代码中,随处可见自定义类、对象。对象可以覆盖类的方法,如下:
var field = new Ext.form.NumberField({ allowBlank: false, allowNegative: false, allowDecimals: false, validateValue: function (v) { // 方法重写 this.record._valid[this.col] = Ext.form.NumberField.prototype.validateValue.call(this, v); // 重点 return true; } });
java中,只存在类之间的方法重写。JS的这种情况是由于模拟'类-对象'导致的。
对于ext继承不清楚的同学,可能对于上述代码比较迷惑,尤其是对象field,方法validateValue;类Ext.form.NumberField,方法validateValue的关系比较模糊。
一个简单的小例子,可以说明一切:
var Store = function(){ // 类定义 }; Store.prototype.sing = function(){ // 类方法 console.log('hello'); }; var _store = new Store(); // 对象 _store.sing = function(){ // 对象方法 Store.prototype.sing.call(this); // 访问类方法 console.log('wy'); }; _store.sing(); // hello wy