var generic = { name: null abc: 42 }; var alice = Object.create(generic);
This is how prototypal object inheritence normally works.
It is similar to classical inheritance in other languages, but
works directly from one hashtable to another, and the link is
live (not a copy or merge).
Using new Foo(x) in JavaScript basically does the following:
- obj = Object.create(Foo.prototype);
- Foo.call(obj, x)
- return obj
Despite prototypal inheritance being at the core of the language,
it was not exposed directly in the early versions of the standard
library functions. Instead, a funny trick emerged:
function my_create(parentObj) { function Dummy() {} Dummy.prototype = parentObject; return new Dummy(); } var generic = { name: null abc: 42 }; var alice = my_create(generic);
In the early days, before this trick become well-known, people
really wanted to have class-like behaviours in JavaScript including
to be able to extend another class. Short of a built-in way to
do it, it became common to do:
ChildClass.prototype = new ParentClass();
This has the downside of needlessly creating an instance,
requiring the constructor to be executed and with valid arguments,
and in addition to creating an object that inherits ParentClass.prototype,
the object is also given the instance properties that the constructor
might create which can be really confusing at times.