JavaScript
[JavaScript] 자바스크립트 다형성, 메서드오버라이딩 흉내내기
힘없는염소
2016. 9. 21. 11:21
// 인터페이스function Runable() {// 추상메서드this.run = function() {throw new Error("run메서드 미구현");}}// 구현클래스// RunImpl에서 run메서드를 구현하지 않으면 부모클래스에서 에러를 던진다. (구현강제)function RunImpl() {// Overridethis.run = function() {console.log("달려!!!!");}}RunImpl.prototype = new Runable(); // 상속var man = new RunImpl(); // 객체생성// 부모클래스에 같은 이름의 메서드가 있어도 부모클래스를 상속받은 구현클래스의 재정의된 메서드가 실행된다.// (Scope chain(스코프체인체인)에서 가장 먼저 발견된 메서드를 실행하기 때문이다)man.run();// 다형성 체크// instanceof : 개체가 특정 클래스의 인스턴스인지 여부console.log(man instanceof Object); // trueconsole.log(man instanceof Runable); // trueconsole.log(man instanceof RunImpl); // true
반응형