C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript Object.setPrototypeOf() MethodThe Object.setPrototypeOf() method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null. All JavaScript objects inherit properties and methods from a prototype. It is generally considered the proper way to set the prototype of an object. Syntax:Object.setPrototypeOf(obj, prototype) Parameters:obj: It is the object which is to have its prototype set. Prototype: It is the object's new prototype (an object or null). Return value:This method returns the specified object. Browser Support:
Example 1let raay = { drive() { return 'Add raay'; } } let naty = { net() { return 'use net'; } } // Set raay's __proto__ to naty's __proto__'s __proto__ Object.setPrototypeOf(naty, raay); console.dir(naty); //prints the naty object console.log(naty.net()); // use net console.log(naty.drive()); // Add raay Output: [object Object] { drive: drive() { return 'Add raay'; }, net: net() { return 'use net'; } } "use net" "Add raay" Example 2var Animal = { speak() { console.log(this.name + ' makes'); } }; class Dog { constructor(name) { this.name = name; } } Object.setPrototypeOf(Dog.prototype, Animal); // If you do not do this you will get a TypeError when you invoke speak var d = new Dog('people'); d.speak(); Output: "people makes" Example 3let toyota = { drive() { return 'driving toyota'; } } let camry = { wifi() { return 'carry'; } } // Set toyota's __proto__ to camry's __proto__'s __proto__ Object.setPrototypeOf(camry, toyota); console.dir(camry); //prints the camry object console.log(camry.wifi()); // carry Output: [object Object] { drive: drive() { return 'driving toyota'; }, wifi: wifi() { return 'carry'; } } "carry"
Next TopicJavaScript Objects
|