0

I'm a somewhat beginner, I used to know the very basics but stopped programming after that.

In JavaScript's Prototypal Inheritance, I've found/learned two ways of doing this.

Using the prototype property of a constructor:

function Mammal(name) {
    this.name = name,
    this.order = "Mammal",

    this.sayHi = function() {
        console.log("My name is " + this.name);
    }
}

function Cat(name) {
    this.name = name;
    this.family = "Felidae";
}

Cat.prototype = new Mammal();

let lion = new Cat("Lion");

Or by calling the Mammal.call(this, name) method.

What are the differences between the two results? Which one is to be preferred if they're different?

  • 3
    Neither one is to be preferred; a combination of the two is closer to the correct version, which is `Cat.prototype = Object.create(Mammal.prototype);`, `Mammal.call(this, name);` in `Cat`, and putting `sayHi` on `Mammal.prototype`. Better, use a class, which does all this and also improves other behaviours. `class Cat extends Mammal {}` – Ry- Nov 14 '21 at 12:48

1 Answers1

0

Usually, we use class keyword to define a class in many program languages. In Javascript you can define your classes using simple and clear syntax using class keyword.

Either you can use the two ways you mentioned, you can use class keyword:

class Mammal {
  constructor(name) {
    this.name = name;
    this.order = 'Mammal';
  }

  sayHi() {
    console.log('My name is ' + this.name);
  }
}

class Cat extends Mammal {
  constructor(props) {
    super(props);
    this.family = 'Felidae';
  }
}

let lion = new Cat('Lion');

lion.sayHi();

Read more about classes on MDN or W3S

nima
  • 7,796
  • 12
  • 36
  • 53
  • If the `class` keyword is just synctactical sugar, which method is it using under the hood, `call()` or `property` ? – Abhinav Jha Nov 15 '21 at 03:48
  • 1
    @Kaiser *"syntactical sugar"* is not correct properly at all, there are many sources you can read about this misleading keyword: https://medium.com/@naveenkarippai/debunking-fake-classes-in-javascript-78f67a6b5c96 and https://webreflection.medium.com/js-classes-are-not-just-syntactic-sugar-28690fedf078 also read https://javascript.info/class and https://stackoverflow.com/questions/36419713/are-es6-classes-just-syntactic-sugar-for-the-prototypal-pattern-in-javascript/47671709 – nima Nov 15 '21 at 09:52
  • 1
    I appreciate your help. Thanks! – Abhinav Jha Nov 15 '21 at 11:04