从继承实例创建 javascript 基础 class 对象

Create a javascript base class object from an inherited instance

我在这里使用公认的答案来实现继承:Javascript inheritance: call super-constructor or use prototype chain?。所以我有一个继承自 Class A 的 Class B。Class B 在它的原型上有 properties/functions 专用于 Class B 对象。

编辑:更清楚地说,我已经设置了继承链,这不是我需要帮助的。对象定义如下:

function classA() {
    this.name= '';
    this.sex = '';
}

function classB(){
  classA.call(this, arguments);
  this.age= 0;
}

在我的代码中,我创建了一个新的 Class B 对象并设置了一些属性:

var _b = new ClassB();
_b.name = 'mike';   -- name is a property of ClassA
_b.sex = 'none';    -- sex  a property of ClassA
_b.age = 20;        -- age is only a property of Classb

我正在调用一个只接受 "type" ClassA 对象的 API。所以我需要创建一个 ClassA 对象并将它的所有属性设置为来自 _b 的值,但只有 ClassA.

的属性

在此示例中,新创建的 ClassA 对象将是这样的: { 姓名:'mike', 性别:'none' }

有没有办法在不显式设置每个 属性 的情况下做到这一点?

var _a = new ClassA();
_a.name = _b.name;
_a.sex = _b.sex;

我不想每次向 ClassA

添加新的 属性 时都必须更改代码

如果对象类型仅由 checking/matching 键确定,创建适配器是一个简单的解决方案。如果您正在检查原型以确定对象类型,您可以在适配器中为 newObj 实例化一个该类型的空对象。

var foo = {
    a: 'alpha',
    b: 'beta',
};

var bar = {
    a: 'alfa',
    b: 'bravo',
    c: 'charlie'
};

function adapt(objA, objB) {//only copy properties common to objA from objB
    var newObj = {};
    for (var prop in objA) {
        var val = objB[prop];
        newObj[prop] = val;
    }

    return newObj;
}

console.log(adapt(foo, bar));