使用美元.使用用户定义的对象扩展

Use $.extend with user defined object

本文关键字:对象 扩展 用户 美元 定义      更新时间:2023-09-26

我正在使用的一个库(DataTables)接受用所有自定义选项声明的对象。

当库尝试使用类似$.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

任何想法为什么会发生这种情况和一些建议如何修复它?

$.extend的最终结果是对象conf到目标对象{}的浅拷贝。

但是,它不会改变目标对象的原型。因此,当实例属性从conf复制到{}时,{}不会成为ExtendedConfBaseConf的实例,因此不携带initComplete方法。

你可以做的是,除了{}之外,你可以使用Object.create来创建一个原型是ExtendedConf原型的对象。这样,结果对象继承ExtendedConf。之后,使用jQuery的$.extend来复制实例属性。

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