proto-extend
v1.0.0
Published
Extend objects in JavaScript using the prototype chain
Downloads
14
Readme
proto-extend
A tiny library that provides a function to create a prototype chain from multiple objects.
Usage
var extend = require('proto-extend');
var a = { id: 'a', foo: 1 };
var b = { id: 'b', bar: 2 };
var c = { id: 'c', baz: 3 };
var chain = extend(a, b, c);
The above returns a new object with a prototype chain of the following:
Object.prototype -> a -> b -> c
and has the properties:
{
id: 'c',
foo: 1,
bar: 2,
baz: 3
}
For more information on how the prototype chain works, see the MDN article Inheritance and the prototype chain.
API
extend(base, extensions...) -> Object
The main export. Takes a base and any number of extension objects and returns a
new object. If the base is not an object, null
will be used instead. Each
extension is converted to a property descriptor map and a new object is created.
Extensions that are not an object are ignored.
extend.getOwnPropertyDescriptorMap(object) -> Object
A helper function used internally but exposed for convenience. It uses the
native methods on Object for getting a list of property names and property
descriptors and creates a map. The main purpose is to feed the second argument
of Object.create()
.
extend.flatten(object[, base]) -> Object
A helper function that takes a prototype chain and flattens it into a new single
object. This is useful if you are passing a prototypal-extended object to a
library that intentionally iterates over only "own" keys. If you specify a
base
, it will stop flattening when it reaches a prototype of that object. By
default, this is Object.prototype
, though it will always stop if it reaches
the null
prototype.