jQuery扩展了原型

cle*_*ort 1 javascript jquery

嗨,我对jQuery和JavaScript相对较新,并对...的功能有疑问$.extend.我extend用来覆盖扩展"基类"的类的原型.让我们调用基Parent和儿童/扩展类AB.现在,当我使用$.extend(true, A.prototype, {someObject: {extraKey: 'value'}});它时,似乎原型Parent的内容也发生了变化someObject,如果几个对象/类继承自父项,则会导致非常奇怪的行为.这也只有在使用"深度"扩展时才会发生.

我设法通过使用相应的原型扩展一个空对象然后使用extend的返回值作为新原型来避免这个问题.例如A.prototype = $.extend(true, {}, A.prototype, {someObject: {extraKey: 'value'}});

为了显示问题,我创建了这个小jsfiddle:http://jsfiddle.net/x8UtF/12/

实际的问题:有没有办法绕过空的物体和东西去 extend(true, X.prototype, {});

Šim*_*das 8

所以,当你这样做时:

$.extend( true, A.prototype, {
    someObject: {Aone: 1, Atwo: 2}
});
Run Code Online (Sandbox Code Playgroud)

结果会发生这种情况:

  1. 属性"Aone","Atwo"将被分配给Parent.prototype.someObject,而不是A.prototype.someObject(在那一点上不存在事件).
  2. A.prototype.someObject将创建该属性并将其值设置为Parent.prototype.someObject.

所以,无论是A.prototype.someObjectParent.prototype.someObject将指向同一个对象:

A.prototype.someObject === Parent.prototype.someObject // true
Run Code Online (Sandbox Code Playgroud)

当然,这不是你想要的.


话虽如此,我担心你的模式不好.A.prototype应该继承Parent.prototype,但你复制从价值观Parent.prototype.someObjectA.prototype.someObject.

此外,您当前的解决方案:

A.prototype = $.extend( true, {}, A.prototype, {
    someObject: {Aone: 1, Atwo: 2}
});
Run Code Online (Sandbox Code Playgroud)

不直观.解密代码正在做什么并不容易.我建议重新评估该模式.(当然,您可以向Stack Overflow寻求帮助.)