Carlo Vallerga Carlo Vallerga - 2 months ago 17
jQuery Question

Use $.extend with user defined object

A library that i'm using (DataTables) accept a object declared with all customized options.

The code fail when the library try to build the result configuration with something like

$.extend({}, defaults , confs)
and receive a user defined object.
Unfortunately all the method defined in
confs
are missing in the result of
$.extend


This code explain what am i trying to do:

class BaseConf {
constructor() {
this.ordering = false;
}
initComplete() {
console.log('BaseConf.foo executed');
}
}

class ExtendedConf extends BaseConf {
initComplete() {
super.foo();
console.log('ExtendedConf.foo executed');
}
}

conf = new ExtendedConf();


mergedConf = $.extend({}, conf);

console.log(mergedConf.ordering); // <-- print false
console.log(mergedConf.initComplete); // <-- print undefined


Any idea of why this happen and some suggestion to how fix it?

Answer

The end result of $.extend is a shallow copy of the object conf to the target object {}.

However, it does not alter the prototype of the target object. So while the instance properties are copied over from conf to {}, {} does not become an instance of either ExtendedConf or BaseConf, therefore does not carry the initComplete method.

What you could do is instead of just {}, you could use Object.create to create an object whose prototype is ExtendedConf's prototype. That way, the resulting object inherits ExtendedConf. After which, use jQuery's $.extend to copy over the instance properties.

var conf = $.extend(Object.create(ExtendedConf.prototype), conf);
Comments