JavaScript 인터페이스를 모방하는 세 가지 방법이 있습니다. 1. 댓글 방법 2. 속성 방법 3. 오리 스타일 모양 식별 방법
1. 댓글 방법 : 이 방법은 프로그램 문서의 범주에 속하며 인터페이스의 상속 및 구현은 프로그래머에 의식적으로 의식적으로 의존합니다.
/*인터페이스 people {function createhead (); function createbody ();}*/var woman = function (name) {// 사람 interfacethis.name = name;} woman.prototyp.showname = function () {alert (this.name); ");} woman.prototype.createhead = function () {alert ("헤드가 만들어졌다 ");}// 2. 속성 확인 방법 : 클래스 속성 목록에 구현할 인터페이스 메소드를 추가하고 정의 된 감지를 통해 해당 메소드가 구현되었는지 반복적으로 확인하십시오.
// 장단점 : 프로그래머가 인터페이스를 구현하도록 강요 할 수 있으며, 인식하지 못하면 오류를보고합니다. 그러나 구현 한 방법을 선언하지만 구현 중에 누락이 발생할 수 있습니다.
/*인터페이스 인민 {function keatehead (); function createbody ();}*/var woman = function (name) {this.name = name; this.implesmentsInterfaces = [ 'people'];} woman.prototype.showname = function () {alert (this.name);} woman.prototype.createbody = function () {// ");} woman.prototype.createhead = function () {alert ("헤드가 만들어졌다 ");} 함수 구현 (obj, interfaces) {for (var i = 1; i <interfaces.length; length; i ++) {var interfacename = interfaces [i]; var interfacefound = false; for (for) j = 0; if (! 구현 (instance, interfaces)) {Throw new Error ( "객체가 필요한 인터페이스를 구현하지 않음");}}3. 오리 스타일 식별 방법 : ( 오리는 외모에 의해 판단되지는 않지만 오리의 특성이 있는지 여부에 의해 판단됩니다. James Whitcomb Riley가 말했듯이, 오리처럼 걷고 다투는 사람은 오리입니다)
위의 두 가지 모두 인터페이스를 구현했다고 선언하지만 진술은 중요하지 않습니다. 인터페이스의 구현의 핵심은 클래스가 인터페이스 메소드 세트를 구현한다는 것입니다. 클래스에 정의 된 인터페이스와 동일한 메소드 함수 이름이있는 함수가있는 경우 인터페이스를 구현하는 것으로 간주됩니다.
// 인터페이스 클래스, 인터페이스 var interface = function (name, motheds) {if (agruments.length! = 2) { "+arguments.length+"인수가있는 인터페이스 생성자 ( "인터페이스 생성자, 정확히 2"); 어머니 [i]! == 'string') {Throw New Error ( '인터페이스 생성자는 Mothed Names가'+'가 문자열로 전달 될 것으로 예상합니다. "+arguments.length+"인수이지만 정확히 1 ")} (var i = 0; i <objs.length; i ++) {var obj = objs [i]; for (var j = 0; j this.motheds.length; 'function') {새 오류 ( 'function interface.ensureimplements : interface'+this.name+', obj.mothed'+mothed+'를 찾지 못했다'); 이름; this.implementsInterfaces = [ 'people'];} woman.prototype.showname = function () {alert (this.name);} woman.prototype.createbody = function () {// 필요한 메소드 경보 구현 ( "여자의 신체가 만들어졌다") ");} // 서브 클래스 var man = function (name) {this.name = name; this.implesmentsinterfaces = [ 'people'];} man.prototype.showname = function () {alert (this.name);} man.prototype.createbody = function () {// 필요한 메소드 알림을 구현합니다. = function () {alert ( "남자의 머리가 만들어졌다");} // poeple.ensureimplements ([ 'woman', 'man'])를 구현할지 여부를 방어합니다.