简体   繁体   中英

Create a javascript base class object from an inherited instance

I'm using the accepted answer here to implement inheritance: Javascript inheritance: call super-constructor or use prototype chain? . So I have a Class B that inherits from Class A. Class B has properties/functions on it's prototype exclusive to Class B objects.

EDIT: to be more clear, I've already setup the inheritance chain, that's not what I need help with. The objects are defined like this:

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

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

In my code, i've created a new Class B object and set some properties:

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

I'm calling an API that will only accept an object of "type" ClassA. So I need to create a ClassA object and set all it's properties to the values coming from _b, but only the properties that are properties of ClassA.

In this example, the newly created ClassA object will be this: { name: 'mike', sex: 'none' }

Is there a way to do this without explicitly setting each property?

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

I don't want to have to change the code every time I add a new property to ClassA

If the object type is simply determined by the checking/matching keys, creating an adapter is a simple solution. If you are checking prototype to determine Object type, you can instantiate an empty object of that type for newObj in the adapter.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM