Metode JavaScript Object.setPrototypeOf () menyetel prototipe dari objek tertentu ke objek lain atau null.
Sintaks dari setPrototypeOf()
metode ini adalah:
Object.setPrototypeOf(obj, prototype)
The setPrototypeOf()
metode, menjadi metode statis, disebut menggunakan Object
nama kelas.
Parameter setPrototypeOf ()
The setPrototypeOf()
Metode mengambil di:
- obj - Objek yang memiliki set prototipe.
- prototipe - Prototipe baru objek (objek atau null).
Kembalikan nilai dari setPrototypeOf ()
- Mengembalikan objek yang ditentukan.
Catatan: Mengubah ((Prototype))
sebuah objek saat ini merupakan operasi yang sangat lambat di setiap browser dan mesin JavaScript.
Contoh 1: Menggunakan 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!
Keluaran
Marcus, gonggong!
Contoh 2: Menggunakan 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!
Keluaran
nama: "Marcus" suara: "gonggongan" __proto__: konstruktor: kelas Anjing memperkenalkan: ƒ perkenalkan () __proto__: makeSound: ƒ makeSound () __proto__: Objek Marcus, gonggong!
Bacaan yang Disarankan: Javascript Object isPrototypeOf ()