>  기사  >  웹 프론트엔드  >  JavaScript 인터페이스 구현 코드(Interfaces In JavaScript)_js 객체 지향

JavaScript 인터페이스 구현 코드(Interfaces In JavaScript)_js 객체 지향

WBOY
WBOY원래의
2016-05-16 18:25:151191검색

실제로는 주석으로 인터페이스를 정의하고 실제 코드로 구현할 수 있습니다
예:

코드 복사 코드
/*
interface Composite {
function add(child)
function delete(child)
function getChild(index); 🎜>interface FormItem {
function save();
}
*/
var CompositeForm = function(id, method, action) { // Composite, FormItem 구현
...
};
// CompositeForm.prototype.add = function(child) {
...
}
CompositeForm.prototype.remove = function( child) {
...
};
CompositeForm.prototype.getChild = function(index) {
...
}// FormItem 인터페이스를 구현합니다. 🎜>CompositeForm.prototype.save = function() {
...
};


인터페이스를 구현한 프로그래머가 이러한 인터페이스를 모두 구현했습니까? 우리는 그것을 보장할 수 없습니다! 인터페이스가 구현되었는지 확인할 방법이 없기 때문에
인터페이스가 구현되었는지 확인하는 메커니즘이 필요합니다. 다음과 같습니다.



코드 복사
코드는 다음과 같습니다. /* interface Composite { function add(child) function delete(child); function getChild(index);
}
interface FormItem {
function save()
}
*/
var CompositeForm = function(id, method, action) {
this.implementsInterfaces = ['Composite', 'FormItem'];
...
}
...
function addForm(formInstance) {
if(!implements(formInstance) , 'Composite', 'FormItem' )) {
throw new Error("개체가 필수 인터페이스를 구현하지 않습니다.")
}
...
}
// 개체가
// 필요한 인터페이스를 구현한다고 선언하는지 확인하는 함수를 구현합니다.
function Implements(object) {
for(var i = 1; i var interfaceName = 인수[i]
var interfaceFound =
for(var j = 0; j < object.implementsInterfaces.length; j ) {
if(object.implementsInterfaces[j] == 인터페이스 이름) {
interfaceFound =
break;
}

if(!interfaceFound) {
return false; // 인터페이스를 찾지 못했습니다.
}
}
return true;
}

이 메소드를 사용하면 프로그래머는 작성할 때 어떤 인터페이스가 구현되는지 표시할 수 있습니다. this.implementsInterfaces = ['Composite', 'FormItem']; 호출할 때 Implements 메소드를 사용하여 구현 가능 여부를 확인합니다. 구현이 'Composite' 인터페이스로 작성되었을 가능성이 높지만 코드에 add 메소드가 없습니다. 따라서 인터페이스를 구현하는 클래스에 인터페이스의 메소드가 포함되어 있는지 확인해야 합니다! 따라서 인터페이스에는 주석이 없어야 합니다.




코드 복사

코드는 다음과 같습니다.
...
function addForm (formInstance) {
Interface.ensureImplements(formInstance, Composite, FormItem);
// 이 함수는 필수 메소드가 구현되지 않은 경우 오류를 발생시킵니다.
// 함수 실행을 중단합니다. >// 이 줄 아래의 모든 코드는 검사가 통과된 경우에만 실행됩니다.
...
}

는 Composite, FormItem 및 CompositeForm 인터페이스를 정의합니다. Interface.ensureImplements를 사용하여 formInstance가 이 두 인터페이스의 모든 메소드를 구현하는지 확인하십시오.
인터페이스의 정의를 살펴보겠습니다. 매개변수는 두 개입니다. 첫 번째 매개변수는 인터페이스 이름이고, 두 번째 매개변수는 인터페이스에 포함된 메서드 배열입니다.




코드 복사

코드는 다음과 같습니다.

// Constructor.
var Interface = function(name,methods) { if(arguments.length ! = 2) { throw new Error("인터페이스 생성자가 "argument.length "인수로 호출되었지만 정확히 2가 필요합니다.") this.name = name; this.methods = []; for(var i = 0, len =methods.length; i < len; i ) { if(typeofmethods[i] !== 'string') {
throw new Error(" 인터페이스 생성자는 메서드 이름이 "
"문자열로 전달될 것으로 예상합니다.")
}
this.methods.push(methods[i]); }
};
为인터페이스 添加建议接口是否实现적静态방법
复代码 码如下:
// 건설자.
Interface.ensureImplements = function(object) {
if(arguments.length < 2) {
새 Error("Function Interface.ensureImplements가 "
arguments.length "인수로 호출되었지만, 그러나 최소 2개 이상 예상됩니다.");
}
for(var i = 1, len = 인수.길이; i < len; i ) {
var 인터페이스 = 인수[i];
if(interface.constructor !== Interface) {
throw new Error("Function Interface.ensureImplements는 인수를 기대합니다."
"두 개 이상은 인터페이스의 인스턴스입니다.");
}
for(var j = 0, 메소드 Len = 인터페이스.메소드.길이; j < 메소드Len; j ) {
var 메소드 = 인터페이스.메소드[j];
if(!object[method] || typeof object[method] !== 'function') {
throw new Error("Function Interface.ensureImplements: object "
"는 " 인터페이스를 구현하지 않습니다. .name
" 인터페이스. 메소드 " 메소드 "를 찾을 수 없습니다.");
}
}
}
};
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.