Metoda JavaScript Object.setPrototypeOf () setează prototipul unui obiect specificat la alt obiect sau nul.
Sintaxa setPrototypeOf()
metodei este:
Object.setPrototypeOf(obj, prototype)
setPrototypeOf()
Metoda, fiind o metodă statică, se numește folosind Object
numele clasei.
setPrototypeOf () Parametri
setPrototypeOf()
Metoda ia în:
- obj - Obiectul care urmează să aibă setul de prototip.
- prototip - Noul prototip al obiectului (un obiect sau nul).
Returnează valoarea din setPrototypeOf ()
- Returnează obiectul specificat.
Notă: Schimbarea ((Prototype))
unui obiect este în prezent o operație foarte lentă în fiecare motor de browser și JavaScript.
Exemplul 1: Utilizarea 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!
Ieșire
Marcus, latră!
Exemplul 2: Utilizarea 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!
Ieșire
nume: "Marcus" sunet: "scoarță" __proto__: constructor: clasă Câine introduce: ƒ introduce () __proto__: makeSound: ƒ makeSound () __proto__: Obiect Marcus, scoarță!
Citire recomandată: Javascript Object isPrototypeOf ()