0

As the title said, I have two class like below:

class A {
    constructor() {
       this.a = 1
       this.b = 2
    }
}
Class B extends A {
    constructor() {
       super()
       this.c = 3
    }
}

Now, I instance class B

const b1 = new B()

Can I use some method to get the { a:1, b:2 } from b1. Because I need to post some data through API. But my model is something like class B. but the interface of the API is like class A. So I just want to get the parent object from the child object. Thanks in advance.

8
  • 6
    if B extends A then .... b1.a would be 1, or did I miss something important? Commented Sep 21, 2022 at 10:47
  • but the interface of the API is like class A - an aspect of inheritance in OOP is that every single B object is an A object too, and can be used where A objects are expected. Commented Sep 21, 2022 at 10:53
  • 1
    Practical check: try console.log(b1 instanceof B, b1 instanceof A);. Commented Sep 21, 2022 at 10:55
  • @JaromandaX Yes, you are right. But if the interface of API have a lot of property should be passed. I don't think b1.a b1.b ...... b1.z is a good code. Commented Sep 21, 2022 at 14:00
  • @Courage why is it bad code? This is how JS works, prototypical inheritance. Commented Sep 21, 2022 at 14:01

1 Answer 1

1

Can I use some method to get the { a:1, b:2 } from b1?

I interpret this to mean that you want an object with only properties a and b from b1. If that's your meaning, then you can simply pick those properties from b1 and post the new object:

function pick (obj, keys) {
  const result = {};
  for (const key of keys) result[key] = obj[key];
  return result;
}

class A {
  constructor () {
     this.a = 1;
     this.b = 2;
  }
}

class B extends A {
  constructor () {
     super();
     this.c = 3;
  }
}

const b1 = new B();

// Post this:
const data = pick(b1, ['a', 'b']);

console.log(data); // { a: 1, b: 2 }

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your response. But what I want is some decent way. Like downcasting or upcasting in JAVA
@Courage do not expect JavaScript to work like Java, they're not the same. JS doesn't have those concepts. Also have a look at stackoverflow.com/questions/44291524/…

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.