New object from prototype
suggest changeIn 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();
};
}
Source: http://javascript.crockford.com/prototypal.html
Object.create()
The Object.create() method creates a new object with the specified prototype object and properties.
Syntax: Object.create(proto[, propertiesObject])
Parameters:
- proto (The object which should be the prototype of the newly-created object.)
- propertiesObject (Optional. If specified and not undefined, an object whose enumerable own properties (that is, those properties defined upon itself and not enumerable properties along its prototype chain) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of Object.defineProperties().)
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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents