0

I'm new to JavaScript and prototype-based programming. I know you can define inherited classes like class Circle extends Shape {}, but class is mostly a syntactic sugar of constructor functions, so is there any equivalent for inheritance of functions in JavaScript?

In other words, how can I define an inherited function without class keyword, like this:

var Shape = function() {
  this.getColor = function() {alert('Some color!')};
};

//Something like this:
var Circle = Function.create(Shape);

var circle1 = new Circle;

//With all below conditions:
console.log(Circle.__proto__ == Shape)                     // true
console.log(Circle.prototype.__proto__ == Shape.prototype) // true
console.log(circle1 instanceof Shape)                      // true
console.log(Object.getOwnPropertyNames(circle1))           // Array [ "getColor" ]

I've searched some articles but last condition wasn't achieved in them and getColor was an inherited property, rather than being a member of the circle1 itself.

  • 3
    There isn't, those keywords are just a part of the "_syntactic sugar_", which classes actually are not (anymore) when we have private instance properties too. – Teemu Feb 15 '22 at 08:54
  • 1
    [This answer](https://stackoverflow.com/a/30783368/157247) (disclosure: it's one of mine) to the linked question shows how to do an inheritance hierarchy with the old `function` syntax. (I also go into it in Chapter 4 of my recent book *JavaScript: The New Toys*; links in my profile.) But while you can do it, there's no particularly good reason to. `class` is simpler, less error-prone, and more powerful. – T.J. Crowder Feb 15 '22 at 08:54
  • 2
    *"...but class is only a syntactic sugar of constructor functions..."* Not anymore. `class` now has private fields and private methods, which there's no direct replacement for using `function` syntax. – T.J. Crowder Feb 15 '22 at 08:55
  • @T.J.Crowder Thanks. I edited the question – Reza Nooralizadeh Feb 15 '22 at 08:58
  • *"With all below conditions: `console.log(Circle.__proto__ == Shape); // true`"* The answer I linked to doesn't show how to do that bit. I'll add it to that answer. – T.J. Crowder Feb 15 '22 at 09:00
  • I've done that now. – T.J. Crowder Feb 15 '22 at 09:07
  • Side note: Don't use the `__proto__` accessor property. It's only defined to support legacy code, and it's "normative optional" meaning a JavaScript engine doesn't have to provide it. Also, not all objects have it, because it's defined on `Object.prototype`, and not all objects inherit from `Object.prototype` (though of course the vast, vast majority do). – T.J. Crowder Feb 15 '22 at 09:19
  • I found the answer. `var Circle = function() { Shape.call(this); }; Circle.prototype.constructor = Circle; Object.setPrototypeOf(Circle.prototype, Shape.prototype); Object.setPrototypeOf(Circle, Shape); ` – Reza Nooralizadeh Feb 15 '22 at 13:44

0 Answers0