Javascript 主干:将模型转换为不同模型类的最佳方式

Javascript 主干:将模型转换为不同模型类的最佳方式,javascript,backbone.js,Javascript,Backbone.js,我有几个主干模型: var MainThing = Backbone.Model(/* some methods */); var CustomerFacingThing = MainThing.extend(/* overrides of those methods */); 在代码中的几个地方,我有一个MainThing实例,但我想将其转换为CustomerFacingThing,以便将其传递给客户编写的代码: var mainThing = new MainThing(); custo

我有几个主干模型:

var MainThing = Backbone.Model(/* some methods */);

var CustomerFacingThing = MainThing.extend(/* overrides of those methods */);
在代码中的几个地方,我有一个
MainThing
实例,但我想将其转换为
CustomerFacingThing
,以便将其传递给客户编写的代码:

var mainThing = new MainThing();
customerFunction(mainThing.convertToCustomerFacingThing());
我的问题是,最好的方法是什么?我能想到的一种方法是改变原型:

mainThing.prototype = CustomerFacingThing.prototype;
但这不会改变“隐藏原型”,因此我不确定这是否可行(例如,我不确定CustomerFacingThing的主要实例是否为
true

我还可以将属性和事件复制到新的
CustomerFacingThing
实例:

var customerFacingVersion = new CustomerFacingThing();
customerFacingVersion.attributes = mainThing.attributes;
customerFacingVersion.events = mainThing.events;
但是,由于事件在那一点上已经确定,我也不确定这是否有效。另外,
mainThing
可能具有非属性属性,因此我必须执行以下操作:

_(mainThing).each(function(value, key) {
    customerFacingThing[key] = value;
});
但这会用这些方法的主要版本覆盖实例上面向客户的方法


那么,谁能解释一下更改主干.Model实例类的最佳方法吗?

我建议使用CustomerFacingThing构造函数,并将main作为参数传入。
由于主干.Models将其数据存储在属性中,因此以下代码应相同:

var mainThing = new MainThing();
var customerThing = new CustomerThing();
mainThing.get('propertyName') == customerThing.get('propertyName');
然后可以在构造函数中使用以下代码:
注意这是TypeScript语法

class ListItem extends Backbone.Model implements IListItem {
    get Id(): number { return this.get('Id'); }
    set Id(value: number) { this.set('Id', value); }
    set Name(value: string) { this.set('Name', value); }
    get Name(): string { return this.get('Name'); }

    constructor(input: IListItem) {
        super();
        for (var key in input) {
            if (key) {
                this[key] = input[key];
            }
        }
    }
}
有关此技术的详细信息,请参见: