--- title: Object.create() slug: Web/JavaScript/Reference/Global_Objects/Object/create tags: - Creazione - Oggetto - Prototipo - metodo translation_of: Web/JavaScript/Reference/Global_Objects/Object/create ---
Il metodo Object.create()
crea un nuovo oggetto a partire dall'oggetto prototipo e dalle proprietà specificati.
Object.create(proto[, propertiesObject])
proto
propertiesObject
Lancia un'eccezione di tipo {{jsxref("Global_Objects/TypeError", "TypeError")}} se il parametro proto
non è {{jsxref("Global_Objects/null", "null")}} oppure un oggetto.
Object.create
Sotto, trovi un esempio di come implementare un'ereditarietà classica usando Object.create
. Si tratta di un'ereditarietà singola, l'unica supportata da Javascript.
// 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.'
Se desideri ereditare proprietà e metodi da oggetti multipli, puoi utilizzare dei mixins.
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 };
La funzione mixin
copia le funzioni dell'oggetto prototype della superclasse nell'oggetto prototype della sottoclasse; la funzione mixin deve essere implementata dall'utente. Un esempio di funzione simil mixin potrebbe essere jQuery.extend.
propertiesObject
con 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); } } }); 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 a adding 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 } });
Questo polyfill implementa il caso di utilizzo principale, ovvero creare un nuovo oggetto specificando un oggetto prototipo, ma non prende in considerazione il secondo argomento dell'API orginale.
if (typeof Object.create != 'function') { Object.create = (function() { var Object = 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'); } Object.prototype = prototype; var result = new Object(); Object.prototype = null; return result; }; })(); }
Specifica | Stato | Commento |
---|---|---|
{{SpecName('ES5.1', '#sec-15.2.3.5', 'Object.create')}} | {{Spec2('ES5.1')}} | Definizione iniziale. Implementato in JavaScript 1.8.5. |
{{SpecName('ES6', '#sec-object.create', 'Object.create')}} | {{Spec2('ES6')}} |
Caratteristica | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Supporto base | {{CompatChrome("5")}} | {{CompatGeckoDesktop("2")}} | {{CompatIE("9")}} | {{CompatOpera("11.60")}} | {{CompatSafari("5")}} |
Caratteristica | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Supporto base | {{CompatVersionUnknown}} | {{CompatVersionUnknown}} | {{CompatGeckoDesktop("2")}} | {{CompatVersionUnknown}} | {{CompatOperaMobile("11.50")}} | {{CompatVersionUnknown}} |
Basato sulla tabella di compatibilità di Kangax.