简体   繁体   English

为什么 jQuery 的深层复制不复制描述性属性?

[英]Why doesn't jQuery's deep copy not copy descriptive properties?

While learning about Object.defineProperty() , I was trying it for deep cloned objects.在学习Object.defineProperty() ,我尝试将其用于深度克隆对象。 Consider the following snippet,考虑以下片段,

 var obj = {}; Object.defineProperty(obj, 'key', { get: () => {return key}, set: (value) => { if (typeof(value) == 'number'){ key = value; } } }); obj.key = 54; console.log(obj.key); // Output: 54 obj.key = ['a', 'b']; console.log(obj.key); // Output: 54 var clone = $.extend(true, {}, obj); clone.key = 44; console.log(obj.key, clone.key); // Output: 54 44 clone.key = 'hello'; console.log(clone.key); // Output: hello
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Why does the clone created by jQuery not maintain the original getters and setters from the object.为什么 jQuery 创建的克隆不维护对象的原始 getter 和 setter。 If I do require this functionality, how can I get deeply cloned objects to have the same getters and setters as their parents?如果我确实需要这个功能,我怎样才能让深度克隆的对象拥有与其父对象相同的 getter 和 setter?

When you define a property using Object.defineProperty , with a descriptor for set , you add an event for the value to be changed.当您使用定义属性Object.defineProperty ,与一个描述符set ,添加一个事件改变的值。 This event is associated with the reference of object.此事件与对象的引用相关联。

When you use $.extend , what it does is, copy its value.当您使用$.extend ,它所做的是复制其值。

Following is the partial code of $.extend以下是$.extend的部分代码

for (; i < length; i++) {

  // Only deal with non-null/undefined values
  if ((options = arguments[i]) != null) {

    // Extend the base object
    for (name in options) {
      src = target[name];
      copy = options[name];

As you see, only the value is copied.如您所见,仅复制值。 The reason why the descriptor is not copied can be that, the intention of having a descriptor would be specific to that object alone and not to its child.不复制描述符的原因可能是,拥有描述符的目的是特定于该对象而不是其子对象。

This behavior is also shared by Object.assign此行为也由Object.assign共享

 var obj = {}; Object.defineProperty(obj, 'key', { get: () => { return key }, set: (value) => { if (typeof(value) == 'number') { key = value; } } }); obj.key = 54; console.log(obj.key); // Output: 54 obj.key = ['a', 'b']; console.log(obj.key); // Output: 54 var clone = Object.assign({}, obj) clone.key = 44; console.log(obj.key, clone.key); // Output: 54 44 clone.key = 'hello'; console.log(clone.key); // Output: hello

I think the problem is the scope of the functions.我认为问题在于功能的范围。 You are not able to clone the scope and to avoid problems they decided to omit functions while cloning.您无法克隆范围并避免在克隆时他们决定省略函数的问题。

But i am not sure about that.但我不确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM