Javascript 对用户定义的对象使用$.extend
我正在使用的库(DataTables)接受使用所有自定义选项声明的对象 当库尝试使用类似于Javascript 对用户定义的对象使用$.extend,javascript,jquery,datatables,ecmascript-6,Javascript,Jquery,Datatables,Ecmascript 6,我正在使用的库(DataTables)接受使用所有自定义选项声明的对象 当库尝试使用类似于$的内容构建结果配置时,代码失败。extend({},defaults,confs)并接收用户定义的对象。 不幸的是,confs中定义的所有方法在$的结果中都丢失了。extend 这段代码解释了我试图做什么: class BaseConf { constructor() { this.ordering = false; } initComplete() {
$的内容构建结果配置时,代码失败。extend({},defaults,confs)
并接收用户定义的对象。
不幸的是,confs
中定义的所有方法在$的结果中都丢失了。extend
这段代码解释了我试图做什么:
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
BaseConf类{
构造函数(){
这个。顺序=假;
}
initComplete(){
log('BaseConf.foo executed');
}
}
类ExtendedConf扩展BaseConf{
initComplete(){
super.foo();
log('ExtendedConf.foo executed');
}
}
conf=新的ExtendedConf();
mergedConf=$.extend({},conf);
console.log(mergedConf.ordering);// $.extend
的最终结果是对象conf
到目标对象{}
的浅拷贝
但是,它不会改变目标对象的原型。因此,当实例属性从conf
复制到{}
时,{}
不会成为ExtendedConf
或BaseConf
的实例,因此不携带initComplete
方法
您可以使用Object.create
创建一个对象,其原型是ExtendedConf
的原型,而不仅仅是{}
。这样,生成的对象将继承ExtendedConf
。之后,使用jQuery的$.extend
复制实例属性
var conf = $.extend(Object.create(ExtendedConf.prototype), conf);
好了,现在我明白了我的代码失败的原因,所以唯一的解决方案就是更改库中的代码以避免使用$.extend?