Javascript Object.setPrototypeOf ()

Metode JavaScript Object.setPrototypeOf () nosaka noteikta objekta prototipu citam objektam vai nulli.

Metodes sintakse setPrototypeOf()ir šāda:

 Object.setPrototypeOf(obj, prototype)

setPrototypeOf()Metodi, kas ir statiska metode, sauc izmantojot Objectklases nosaukumu.

setPrototypeOf () parametri

setPrototypeOf()Metode ņem in:

  • obj - objekts, kura prototips ir jāiestata.
  • prototips - objekta jaunais prototips (objekts vai nulle).

Atgriezties no setPrototypeOf ()

  • Atgriež norādīto objektu.

Piezīme.((Prototype)) Objekta maiņa pašlaik ir ļoti lēna darbība katrā pārlūkprogrammā un JavaScript dzinējā.

1. piemērs: Object.setPrototypeOf () izmantošana

 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!

Rezultāts

 Markuss, rej!

2. piemērs: Object.setPrototypeOf () izmantošana

 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!

Rezultāts

 nosaukums: "Markuss" skaņa: "miza" __proto__: konstruktors: klase Suns iepazīstina: ƒ iepazīstina () __proto__: makeSound: ƒ makeSound () __proto__: Objekts Markuss, miza!

Ieteicamā literatūra: Javascript Object isPrototypeOf ()

Interesanti raksti...