简体   繁体   English

为什么新设置的属性不在 jQuery object 上保留,但在 dom 元素上保留?

[英]Why doesn't the newly set property persist on jQuery object but it persists on the dom element?

elem is the dom element with id dummy. elem是 id 为 dummy 的 dom 元素。 jElem is the jquery object wrapped around elem . jElem是 jquery object 包裹在elem上。

obj1 has init method which sets a property on the argument passed to it. obj1具有init方法,该方法在传递给它的参数上设置属性。 Here, it creates a new property prop and sets true on it.在这里,它创建了一个新的属性prop并将其设置为true obj2 is also passed the same argument in its init method. obj2在其init方法中也传递了相同的参数。 obj2 also has showProp method which prints the property set on the argument passed. obj2还具有showProp方法,该方法打印在传递的参数上设置的属性。 Following is the code:以下是代码:

 let elem = document.querySelector("#dummy"); let obj1 = { init(item){ item.prop = true; } }; let obj2 = { init(item){ this.item = item; }, showProp(){ console.log(this.item.prop); } }; obj1.init($(elem)); obj2.init($(elem)); obj2.showProp(); //undefined obj1.init(elem); obj2.init(elem); obj2.showProp(); //true
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="dummy">dummy</div>

My concern is: When jElem is passed in both the objects, the property on jElem is not persisted.我担心的是:当jElem在两个对象中都传递时, jElem 上的属性不会持久化。 But when dom element is passed itself( elem ), the property persists.但是当 dom 元素本身传递时( elem ),该属性仍然存在。 Why is that?这是为什么?

I am so sorry about the misunderstanding.我很抱歉造成误解。 It was actually dumb of me.我真的很傻。 I didn't get sleep and was not able to debug properly.我没有睡觉,也无法正确调试。 The problem was I was writing code as below:问题是我正在编写如下代码:

let elem = document.querySelector("#dummy");

let obj1 = {
  init(item){
    item.prop = true;
  }
};
let obj2 = {
  init(item){
    this.item = item;
  },
  showProp(){
    console.log(this.item.prop);
  }
};
obj1.init($(elem));
obj2.init($(elem));
obj2.showProp(); //undefined

obj1.init(elem);
obj2.init(elem);
obj2.showProp(); //true

This is obviously as expected because I am creating a new jQuery object when passing to the function: obj1.init($(elem)) and obj2.init($(elem));这显然符合预期,因为我在传递给 function 时创建了一个新的 jQuery object: obj1.init($(elem))obj2.init($(elem)); . . Here, obviously both the init methods are passed 2 different objects and not the same object.在这里,显然两个init方法都传递了 2 个不同的对象,而不是同一个 object。

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

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