如何在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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿