La méthode JavaScript Object.setPrototypeOf () définit le prototype d'un objet spécifié sur un autre objet ou sur null.
La syntaxe de la setPrototypeOf()
méthode est:
Object.setPrototypeOf(obj, prototype)
La setPrototypeOf()
méthode, étant une méthode statique, est appelée en utilisant le Object
nom de la classe.
Paramètres setPrototypeOf ()
La setPrototypeOf()
méthode prend en compte:
- obj - L'objet qui doit avoir son prototype défini.
- prototype - Le nouveau prototype de l'objet (un objet ou nul).
Valeur renvoyée par setPrototypeOf ()
- Renvoie l'objet spécifié.
Remarque: la modification ((Prototype))
de l'objet d'un objet est actuellement une opération très lente dans tous les navigateurs et moteurs JavaScript.
Exemple 1: Utilisation d'Object.setPrototypeOf ()
let Animal = ( makeSound() ( console.log(`$(this.name), $(this.sound)!`); ), ); // defining new Dog object function Dog(name) ( this.name = name; this.sound = "bark"; // setting prototype to Animal Object.setPrototypeOf(this, Animal); ) dog1 = new Dog("Marcus"); dog1.makeSound(); // Marcus, bark!
Production
Marcus, aboie!
Exemple 2: Utilisation d'Object.setPrototypeOf ()
let Animal = ( makeSound() ( console.log(`$(this.name), $(this.sound)!`); ), ); // defining object class Dog ( constructor(name, age) ( this.name = name; this.sound = "bark"; ) introduce() ( console.log(`I'm $(this.name). I am $(this.age) years old.`); ) ) // Here Dog.prototype is passed as it is an object, while Dog is not an object Object.setPrototypeOf(Dog.prototype, Animal); dog1 = new Dog("Marcus", 3); console.log(dog1); dog1.makeSound(); // Marcus, bark!
Production
nom: son "Marcus": "aboyer" __proto__: constructeur: classe Chien introduire: ƒ introduire () __proto__: makeSound: ƒ makeSound () __proto__: Objet Marcus, aboyer!
Lecture recommandée: l' objet Javascript isPrototypeOf ()