Skip to content

Instantly share code, notes, and snippets.

@andrewwoods
Created May 22, 2015 20:25
Show Gist options
  • Save andrewwoods/ac4f2e87cf95a961d984 to your computer and use it in GitHub Desktop.
Save andrewwoods/ac4f2e87cf95a961d984 to your computer and use it in GitHub Desktop.
JS OOP inheritance idea
Source URL http://www.sitepoint.com/simple-inheritance-javascript/
This article makes inheritance in OOP easy to understand.
It did get me thinking. In the article above, the author uses
var inheritsFrom = function (child, parent) {
child.prototype = Object.create(parent.prototype);
};
Then calls the function to establish inheritance like this
inheritsFrom(ClassB, ClassA);
When I read the function call above, I feel like it could be misunderstood.
If I wasn't looking at the function definition, it would be easy to pass
the arguments in the wrong order. I was thinking about how to make
it more clear. Here's something I was thinking about
Object.prototype.inherits = function (parent) {
this.prototype = Object.create(parent.prototype);
};
Using this, inheritance could then be written as the following.
ClassB.inherits( ClassA );
Are there any problems that you can see with this approach?
@andrewwoods
Copy link
Author

It just occurred to me that Object might be the wrong "class" to use. That would allow things "firstName".inherits( ClassA ) which is weird. Function is probably more accurate. Like so.

Function.prototype.inherits = function (parent) {
    this.prototype = Object.create(parent.prototype);
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment