Integrating jQuery.extend() with Custom JavaScript Classes

I’m merging jQuery objects with a custom JS class using $.extend. Event callbacks work correctly, but .each iterates plain jQuery objects.

function Widget(status) {
  this.status = status;
}

Widget.prototype.showStatus = function() {
  console.log('Status:', this.status);
};

function setupWidget() {
  let $btn = $('<button></button>');
  $.extend($btn, new Widget(true));
  $btn.on('click', function() { $(this).showStatus(); });
  return $btn;
}

Based on my experience, directly merging a custom class instance with a jQuery object using $.extend is prone to inconsistencies, particularly in scenarios like iteration with .each. This approach can blur the separation between jQuery’s inherent structure and your custom methods. In one of my projects, I managed this by storing the custom object within the element’s data, ensuring that the jQuery object structure remained intact while still providing access to the custom methods. Adopting a pattern that keeps these components separate typically results in a more robust and maintainable design.

In my experience, merging a jQuery object with a custom widget instance using $.extend can sometimes lead to unexpected outcomes, particularly when iterating with .each. I once encountered a similar issue where the extended object lost its special type during iteration. What helped was taking a step back and ensuring that widget methods could be called from within event handlers by storing the widget instance as a property or in a data attribute. This keeps the separation between jQuery’s native behavior and custom logic intact, ensuring both work as expected alongside each other.