如何在JavaScript中实现多态?
多态性
多态 是面向对象编程(OOP)的宗旨之一。它有助于设计对象,使其可以与特定提供的对象共享或覆盖任何行为。多态性 利用继承的 优势来实现这一点。
在以下示例中,子对象(例如“板球”和“网球”)已覆盖从父对象“游戏”调用的“选择”方法,并分别返回了新字符串,如输出所示。另一个子对象“足球”而不是覆盖select 方法,而是共享(继承)了该方法并显示了父字符串,如输出所示。
示例
<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() // overridden the select method to display { new string. return "i love cricket" } var tennis = function() {} tennis.prototype = Object.create(game.prototype); // overridden the select method to display new tennis.prototype.select = function() string { return "i love tennis" } var football = function() {} football.prototype = Object.create(game.prototype); // shared parent property var games = [new game(), new cricket(), new tennis(), new football()]; games.forEach(function(game){ document.write(game.select()); document.write("</br>"); }); </script> </body> </html>
输出结果
i love games and sports i love cricket i love tennis i love games and sports