In JavaScript, any object can be the prototype of another. When an object is created as a prototype of another, it will inherit all of its parent's properties.
var proto = { foo: "foo", bar: () => this.foo };
var obj = Object.create(proto);
console.log(obj.foo);
console.log(obj.bar());
Console output:
> "foo"
> "foo"
NOTE Object.create
is available from ECMAScript 5, but here's a polyfill if you need support for ECMAScript 3
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
Object.create()
The Object.create() method creates a new object with the specified prototype object and properties.
Syntax: Object.create(proto[, propertiesObject])
Parameters:
Return value
A new object with the specified prototype object and properties.
Exceptions
A TypeError exception if the proto parameter isn't null or an object.