【问题标题】:ExtJS 4 Object.prototype failExtJS 4 Object.prototype 失败
【发布时间】:2012-09-03 21:33:34
【问题描述】:

在使用framework ExtJS version 4.1.1.时使用prototype有点问题

起初我在加载 ExtJS 之前制作了原型。 在"Array.prototype.xyz" and "String.prototype.xyz" 上一切正常。 "Object.prototype.xyz" 上的机器人在包含 ExtJS 的 mixin 中存在不良行为。 示例我的测试代码:

Object.prototype.doSomething = function() {
  console.log('I do it!');
}
var a = {};
a.doSomething();

来自 ExtJS 的错误消息:

Uncaught TypeError: Cannot read property '$childEls' of undefined
And break.

并且: - 是的。如果没有“Uncaught TypeError: Cannot read property '$childEls' of undefined”,它就可以工作 美好的。 - 不。我目前不使用其他 mixins。 - 是的。我尝试只使用一个虚拟面板组件。

问题:Object class-object 上的原型是否有简单的解决方案?

【问题讨论】:

    标签: javascript object extjs extjs4 prototype


    【解决方案1】:

    问题源于 Ext JS 库的基本方法之一:Ext.merge

    证明这一点很简单:

    Object.prototype.doSomething = function(){ console.log("Does something"); };
    
    var emptyObj = {};
    console.log(emptyObj.hasOwnProperty("doSomething"));  // Prints "false"
    
    var mergeObj = Ext.merge({}, {a: "b"});
    console.log(mergeObj.hasOwnProperty("doSomething"));  // Prints "true"
    

    基本上,每次使用对象字面量调用Ext.merge(或Ext.apply)时,您的原型方法都会在原型链上“提升”。当你去创建一个面板(或任何组件,真的)时,类mixin 对象与其原型的mixin 对象合并。由于 mixin 在类定义中被定义为对象字面量,因此您的“doSomething”方法会被提升。

    然后在Ext.util.ElementContainer#getClassChildEls 中,mixin 对象被迭代,假设每个属性都是一个现有的类并尝试访问mixins[name].self.$childEls(其中mixins[name] 是您的“doSomething”方法)。您的方法没有 self 属性,因此访问 $childEls 会引发错误。

    如果您需要每个对象都可用的对象,请将其编写为静态方法,例如 Object.doSomething 甚至 Ext.Object.doSomething

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多