如何在 JavaScript 中实现多态性?
javascriptobject oriented programmingprogramming
多态性
多态性是面向对象编程 (OOP) 的原则之一。它有助于以某种方式设计对象,使它们可以与特定提供的对象共享或覆盖任何行为。多态性利用继承来实现这一点。
在下面的示例中,子对象(例如"cricket"和"tennis")已覆盖从父对象"game"调用的"select"方法,并分别返回一个新字符串,如输出所示。而另一个子对象"football"并没有覆盖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