Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Triển khai Polymorphism (Đa hình) trong JavaScript


Polymorphism (Đa hình)

Một trong 4 trụ cột OOP. Cho phép object con ghi đè (override) hoặc kế thừa (share) hành vi từ object cha. Tận dụng inheritance (kế thừa).

Ví dụ

<html> <body> <script> var game = function () {}; game.prototype.select = function() { return "i love games and sports"; }; var cricket = function() {}; cricket.prototype = Object.create(game.prototype); cricket.prototype.select = function() { return "i love cricket"; }; var tennis = function() {}; tennis.prototype = Object.create(game.prototype); tennis.prototype.select = function() { return "i love tennis"; }; var football = function() {}; football.prototype = Object.create(game.prototype); // football KHÔNG override select() var games = [new game(), new cricket(), new tennis(), new football()]; games.forEach(function(game){ document.write(game.select()); document.write("</br>"); }); </script> </body> </html>

Kết quả

i love games and sports i love cricket i love tennis i love games and sports

Giải thích: cricket, tennis override select(). football kế thừa select() từ game.