Javascript Object.create ()

Il metodo JavaScript Object.create () crea un nuovo oggetto utilizzando il prototipo di un dato oggetto.

La sintassi del create()metodo è:

 Object.create(proto, propertiesObject)

Il create()metodo, essendo un metodo statico, viene chiamato utilizzando il Objectnome della classe.

parametri create ()

Il create()metodo comprende:

  • proto - L'oggetto che dovrebbe essere il prototipo dell'oggetto appena creato.
  • propertiesObject (opzionale) - Un oggetto le cui proprietà enumerabili specificano i descrittori di proprietà da aggiungere all'oggetto appena creato. Queste proprietà corrispondono al secondo argomento di Object.defineProperties().

Valore restituito da create ()

  • Restituisce un nuovo oggetto con l'oggetto prototipo e le proprietà specificati.

Nota: se proto non è nullo an Object, TypeErrorviene lanciato.

Esempio: utilizzo di Object.create ()

 let Animal = ( isHuman: false, sound: "Unspecified", makeSound() ( console.log(this.sound); ), ); // create object from Animal prototype let snake = Object.create(Animal); snake.makeSound(); // Unspecified // properties can be created and overridden snake.sound = "Hiss"; snake.makeSound(); // Hiss // can also directly initialize object properties with second argument let properties = ( isHuman: ( value: true, ), name: ( value: "Jack", enumerable: true, writable: true, ), introduce: ( value: function () ( console.log(`Hey! I am $(this.name).`); ), ), ); human = Object.create(Animal, properties); human.introduce(); // Hey! I am Jack.

Produzione

Sibilo non specificato Hey! Sono Jack.

Lettura consigliata: oggetto Javascript isPrototypeOf ()

Articoli interessanti...