-2

I want to create an inheritance where I have class defined and creating inheritance using function

class ClassA{
    constructor(){
    this.name = "Kanike"
    }
}
function ClassB(jkk){
     new ClassA()
    this.last = jkk
    
}
ClassB.prototype = ClassA.prototype
var myClassB = new ClassB("kel");
alert(myClassB.name)//cant be accessed here
prawin
  • 17
  • 3
  • 2
    Do you mean you want to make a constructor defined with `function` inherit from one defined with `class`? Why? (You should have a good reason, because it’s overcomplicated and provides no portability benefit.) – Ry- Jul 17 '20 at 07:46
  • 3
    You're already using `class`, so why not do it properly and use `class ClassB extends ClassA`? Docs: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance#ECMAScript_2015_Classes –  Jul 17 '20 at 07:47
  • 1
    You can't really make a normal constructor functions "inherit" from classes because to do this properly you would have to invoke the class constructor with a specific `this` value, but class constructors can only be invoked with `new` (with which you can't set `this`). Also `ClassB.prototype = ClassA.prototype` is wrong. Please see https://stackoverflow.com/q/17392857/218196 for more information about how to setup inheritance with constructor functions. But as everyone is saying, just use `class`. – Felix Kling Jul 17 '20 at 07:56
  • @Ry- Actually we have a JS package where everything is in Class's and we have our own Product where we used function-based classes. If there is any solution it highly helps us – prawin Jul 17 '20 at 11:34
  • 1
    @prawin: The solution is for you to switch to `class`. `function` constructors have no advantages except ES5 compatibility, and you can’t extend an ES6 class in any way using only ES5 features. – Ry- Jul 17 '20 at 22:18

1 Answers1

1

This is what the extends keyword is for. Extend the class and you can access both the name and last fields:

class ClassA {
  constructor() {
    this.name = "Kanike";
  }
}

class ClassB extends ClassA {
  constructor(last) {
    super();
    this.last = last;
  }
}

let classB = new ClassB("Kel");
console.log(classB.name, classB.last);
Ry-
  • 218,210
  • 55
  • 464
  • 476
Lewis
  • 4,285
  • 1
  • 23
  • 36