0

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

1
  • You may find this article interesting. Commented Mar 11, 2016 at 21:05

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, yes thats exactly what I need. I was thinking that I didn't explain it very well, glad you understood.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.