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.
const proto = { foo: "foo", bar() { return this.foo; } };
const obj = Object.create(proto);
console.log(obj.foo);
console.log(obj.bar());
Console output:
> "foo"
> "foo"
NOTE Object.create is available from ECMAScript 5. This polyfill covers only the first argument for older engines. It does not accept null and ignores propertiesObject.
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:
- proto (The object which should be the prototype of the newly-created object.)
- propertiesObject (Optional. If specified and not
undefined, an object whose own enumerable properties are property descriptors to add to the new object. This is the same kind of argumentObject.defineProperties()accepts.)
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