다형성
다형성 객체 지향 프로그래밍(OOP)의 핵심 중 하나입니다. 특정 제공된 개체와 동작을 공유하거나 재정의할 수 있는 방식으로 개체를 디자인하는 데 도움이 됩니다. 다형성 상속을 활용합니다. 이를 위해.
다음 예제에서는 'cricket ' 및 '테니스 '이(가) 'select를 재정의했습니다. ' 상위 개체 'game에서 호출된 메서드 ' 및 출력에 표시된 대로 각각 새 문자열을 반환했습니다. 반면에 다른 자식 개체는 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