Skip to content

Instantly share code, notes, and snippets.

@jeremyckahn
Created May 12, 2013 01:07
Show Gist options
  • Select an option

  • Save jeremyckahn/5561999 to your computer and use it in GitHub Desktop.

Select an option

Save jeremyckahn/5561999 to your computer and use it in GitHub Desktop.
@getify's saved gist comment #2
@jeremyckahn
> This works in ES3 and `Object.create` does not
Actually, the [non-ES5 polyfilly for `Object.create()`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create#Polyfill) is:
```js
Object.create = function(o) {
function F(){}
F.prototype = o;
return new F();
};
```
That way, you can indeed use the `Object.create()` style of code I suggest is usable in all browsers, even without ES5.
As I look more closely at your above `inherit()`, I realize that my previous comment too hastily claimed an extra object in the chain that is in fact incorrect. Sorry about that.
Interestingly, your `inherit()` is almost identical to `Object.create()`. So:
```js
function Parent(){}
function Child(){}
inherit(Child, Parent);
```
is functionally identical to:
```js
function Parent(){}
function Child(){}
Child.prototype = Object.create(Parent.prototype);
```
They're the same. In both cases, there's just two objects, (awkwardly) labeled here as `Parent.prototype` and `Child.prototype`, that are linked together via `Child`'s `[[Prototype]]` chain.
What you notice is that it's the objects we actually care about. The functions and the `new` calling and all that... that's just unnecessary distractions. The simpler approach:
```js
var Parent = { /*..*/ };
var Child = Object.create(Parent);
```
Same capability, less confusion. That's why I think it's a superior coding pattern.
What that proves is the point of my articles: you're just doing objects linked to objects, and the fact that those objects happen to be attached to functions (`Parent()` and `Child()`) are really irrelevant. I argue that the simpler objects-only approach clears out confusion and misdirection and lets you see clearly and plainly what's really going on.
To me, simpler is better. I don't understand why developers prefer the more verbose and complex way to achieve the same effect. :)
--------
To put a finer point on it, if you're going to drop in a 3-liner "helper" for doing this sort of coding, instead of dropping in `inherit()` as you show above, why not drop in the conditional polyfill for the already ES5 standardized `Object.create()`? Surely using standards is better in its own right?
Then, if you're now using `Object.create()`, it's an easier step to do as I show and drop all the functions and just use the objects. ;-)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment