Esta tradução está incompleta. Ajude atraduzir este artigo.
O método Object.create()
cria um novo objeto com o protótipo de objeto e propriedades especificadas.
Sintaxe
Object.create(proto[, propertiesObject])
Parâmetros
proto
- O objeto que deve ser o protótipo do objeto recém-criado.
propertiesObject
- Opcional. Se especificado e não
undefined
, um objeto cuja as propriedades próprias enumeráveis (isto é, aquelas propriedades definidas sobre si mesmo, e não propriedades enumeráveis ao longo da sua cadeia protótipa) especificam os nomes das propriedades a serem adicionadas ao objeto recém-criado, com os nomes das propriedades correspondentes. Essas propriedades correspondem ao segundo argumentoObject.defineProperties()
.
Throws
Throws a TypeError
exception if the proto
parameter isn't null
or an object.
Exemplos
Classical inheritance with Object.create()
Below is an example of how to use Object.create()
to achieve classical inheritance. This is for single inheritance, which is all that JavaScript supports.
// Shape - superclass function Shape() { this.x = 0; this.y = 0; } // superclass method Shape.prototype.move = function(x, y) { this.x += x; this.y += y; console.info('Shape moved.'); }; // Rectangle - subclass function Rectangle() { Shape.call(this); // call super constructor. } // subclass extends superclass Rectangle.prototype = Object.create(Shape.prototype); Rectangle.prototype.constructor = Rectangle; var rect = new Rectangle(); console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle);// true console.log('Is rect an instance of Shape?', rect instanceof Shape);// true rect.move(1, 1); // Outputs, 'Shape moved.'
If you wish to inherit from multiple objects, then mixins are a possibility.
function MyClass() { SuperClass.call(this); OtherSuperClass.call(this); } MyClass.prototype = Object.create(SuperClass.prototype); // inherit mixin(MyClass.prototype, OtherSuperClass.prototype); // mixin MyClass.prototype.myMethod = function() { // do a thing };
The mixin
function would copy the functions from the superclass prototype to the subclass prototype, the mixin function needs to be supplied by the user. An example of a mixin like function would be jQuery.extend().
Using propertiesObject
argument with Object.create()
var o; // create an object with null as prototype o = Object.create(null); o = {}; // is equivalent to: o = Object.create(Object.prototype); // Example where we create an object with a couple of sample properties. // (Note that the second parameter maps keys to *property descriptors*.) o = Object.create(Object.prototype, { // foo is a regular 'value property' foo: { writable: true, configurable: true, value: 'hello' }, // bar is a getter-and-setter (accessor) property bar: { configurable: false, get: function() { return 10; }, set: function(value) { console.log('Setting `o.bar` to', value); } /* with ES5 Accessors our code can look like this get function() { return 10; }, set function(value) { console.log('setting `o.bar` to', value); } */ } }); function Constructor() {} o = new Constructor(); // is equivalent to: o = Object.create(Constructor.prototype); // Of course, if there is actual initialization code in the // Constructor function, the Object.create() cannot reflect it // Create a new object whose prototype is a new, empty object // and add a single property 'p', with value 42. o = Object.create({}, { p: { value: 42 } }); // by default properties ARE NOT writable, enumerable or configurable: o.p = 24; o.p; // 42 o.q = 12; for (var prop in o) { console.log(prop); } // 'q' delete o.p; // false // to specify an ES3 property o2 = Object.create({}, { p: { value: 42, writable: true, enumerable: true, configurable: true } });
Polyfill
This polyfill covers the main use case which is creating a new object for which the prototype has been chosen but doesn't take the second argument into account.
if (typeof Object.create != 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype != 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); }
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 5.1 (ECMA-262) The definition of 'Object.create' in that specification. |
Standard | Initial definition. Implemented in JavaScript 1.8.5. |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Object.create' in that specification. |
Standard | |
ECMAScript 2016 Draft (7th Edition, ECMA-262) The definition of 'Object.create' in that specification. |
Draft |
Browser compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 5 | 4.0 (2) | 9 | 11.60 | 5 |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | 4.0 (2) | (Yes) | 11.5 | (Yes) |
See also
Object.defineProperty()
Object.defineProperties()
Object.prototype.isPrototypeOf()
- John Resig's post on getPrototypeOf()