programing

JavaScript에는 인터페이스 타입(Java의 'interface' 등)이 있습니까?

yoursource 2022. 12. 31. 20:45
반응형

JavaScript에는 인터페이스 타입(Java의 'interface' 등)이 있습니까?

자바스크립트로 OOP 만드는 법을 배우고 있어요.인터페이스 개념(Java 등의)이 있습니까?interface)?

그래서 청취자를 만들 수 있을 것 같아요.

「이 클래스에는 이러한 함수가 필요합니다」(즉, 인터페이스 자체가 없습니다)라는 개념은, 다음과 같습니다.

  1. JavaScript 상속은 클래스가 아닌 개체를 기반으로 합니다.다음 사항을 깨닫기 전까지는 별 문제가 되지 않습니다.
  2. JavaScript는 매우 역동적인 언어입니다. 적절한 메서드로 오브젝트를 생성하여 인터페이스에 적합하게 만든 모든 것을 정의할 수 있습니다.우연히도 활자 시스템을 전복시키는 것은 매우 쉬워서 애초에 활자 시스템을 만들어 볼 가치가 없을 것이다.

대신 JavaScript는 덕 타이핑이라고 불리는 것을 사용합니다.(JS는 오리처럼 걷고 오리처럼 울부짖는다면 오리입니다.)오브젝트가 quack(), walk() 및 fly() 메서드를 가지고 있는 경우 코드는 "Dukable" 인터페이스를 구현할 필요 없이 걷고, quick하고, 날 수 있는 오브젝트를 예상하는 모든 장소에서 사용할 수 있습니다.인터페이스는 코드가 사용하는 함수의 집합(및 이러한 함수의 반환값)이며, 덕 타이핑을 사용하면 무료로 얻을 수 있습니다.

그렇다고 ''로 전화를 은 아닙니다.some_dog.quack() TypeError는 에러입니다.솔직히 개에게 꽥꽥거리라고 하면 조금 더 큰 문제가 있습니다. 예를 들어, 오리 타이핑은 모든 오리를 일렬로 세울 때 가장 효과적이며, 개들과 오리들을 일반적인 동물로 취급하지 않는 한 함께 어울리게 하지 않습니다.즉, 인터페이스가 유동적이어도, 아직 거기에 있습니다.애초에 개가 꽥꽥거리며 날아갈 것으로 예상하는 코드에 개를 건네주는 것은 종종 오류입니다.

하지만 당신이 옳은 일을 하고 있다고 확신한다면, 당신은 그것을 사용하기 전에 특정 방법의 존재를 테스트함으로써 퀵독 문제를 해결할 수 있다.뭐랄까

if (typeof(someObject.quack) == "function")
{
    // This thing can quack
}

따라서 사용하기 전에 사용할 수 있는 모든 방법을 확인할 수 있습니다.구문이 좀 추하네요조금 더 예쁜 방법이 있습니다.

Object.prototype.can = function(methodName)
{
     return ((typeof this[methodName]) == "function");
};

if (someObject.can("quack"))
{
    someObject.quack();
}

이것은 표준 JavaScript이므로 사용할 가치가 있는 모든 JS 인터프리터에서 작동합니다.그것은 영어처럼 읽는 것의 부가적인 이점이 있다.

브라우저 IE 이외의 에서는 속성이 에 for...in:

Object.defineProperty(Object.prototype, 'can', {
    enumerable: false,
    value: function(method) {
        return (typeof this[method] === 'function');
    }
}

IE7이 입니다..definePropertyIE8에서는 호스트 오브젝트(DOM 요소 등)에서만 동작하는 것으로 알려져 있습니다.되는 경우는, 「」를 사용할 수 ..defineProperty(IE6는 중국 이외에서는 그다지 중요하지 않기 때문에 언급조차 하지 않겠습니다.)

다른 은 코딩 모든 하고 수정하는 을 금지하고 입니다.Object.prototype으로 사용하고 for...in이 점에 관심이 있는 경우, 또는 문제가 있는 (IMO가 망가진) 코드를 사용하고 있는 경우는, 조금 다른 버전을 사용해 주세요.

function can(obj, methodName)
{
     return ((typeof obj[methodName]) == "function");
}

if (can(someObject, "quack"))
{
    someObject.quack();
}

더스틴 디아즈의 '자바스크립트 디자인 패턴' 사본을 집으세요.Duck Typing을 통해 JavaScript 인터페이스를 구현하기 위한 몇 개의 장이 있습니다.그것도 좋은 읽을거리야.아니요. 인터페이스의 언어 네이티브 실장은 없습니다. 타입을 사용해야 합니다.

// example duck typing method
var hasMethods = function(obj /*, method list as strings */){
    var i = 1, methodName;
    while((methodName = arguments[i++])){
        if(typeof obj[methodName] != 'function') {
            return false;
        }
    }
    return true;
}

// in your code
if(hasMethods(obj, 'quak', 'flapWings','waggle')) {
    //  IT'S A DUCK, do your duck thang
}

JavaScript3)에는 JavaScript(ECMAScript 3)가 .implements나중에 사용하기 위해 저장한 예약어입니다.이것은 정확히 이 목적을 위한 것이라고 생각합니다만, 서둘러 사양서를 발표해 버리기 때문에, 현시점에서는 브라우저는 그것을 그대로 두는 것 이외에는 아무것도 하지 않고, 사용하려고 하면 불평을 하는 경우가 있습니다.

만의 것을 은 충분히 .Object.implement(Interface)특정 속성/특정 집합이 특정 객체에 구현되지 않을 때마다 보크가 발생한다는 논리를 가진 메서드.

나는 다음과 같이 만의 표기법을 사용하는 객체 지향에 관한 기사를 썼다.

// Create a 'Dog' class that inherits from 'Animal'
// and implements the 'Mammal' interface
var Dog = Object.extend(Animal, {
    constructor: function(name) {
        Dog.superClass.call(this, name);
    },
    bark: function() {
        alert('woof');
    }
}).implement(Mammal);

이 특정 고양이 가죽을 벗기는 방법은 여러 가지가 있지만, 이것이 제가 인터페이스 구현에 사용한 논리입니다.저는 이 방법을 선호하며, 읽기 쉽고 사용하기 쉽습니다(위에서 보듯이).실시'라는 말은 '라는 방법을 '실시'라는 이죠.Function.prototype문제가 있는 사람도 있겠지만, 저는 그게 잘 작동한다고 생각해요.

Function.prototype.implement = function() {
    // Loop through each interface passed in and then check 
    // that its members are implemented in the context object (this).
    for(var i = 0; i < arguments.length; i++) {
       // .. Check member's logic ..
    }
    // Remember to return the class being tested
    return this;
}

JavaScript 인터페이스:

JavaScript에는 다음이 없습니다.interface입,,, 그종종종종종 다다다다다다JavaScript의 동적 특성 및 프로토타입 상속의 사용과 관련된 이유로 클래스 간에 일관된 인터페이스를 보장하는 것은 어렵습니다. 그러나 그렇게 하는 것은 가능하며 자주 에뮬레이트됩니다.

이 시점에서 JavaScript에서는 인터페이스를 에뮬레이트하는 몇 가지 특별한 방법이 있습니다.접근법의 차이는 보통 몇 가지 요구를 만족시키는 반면 다른 요구는 처리되지 않은 채로 있습니다.대부분의 경우, 가장 견고한 접근 방식은 지나치게 번거롭고 구현자(개발자)의 발목을 잡습니다.

다음은 인터페이스/추상 클래스에 대한 접근법으로, 매우 번거롭지 않고, 설명이 용이하며, Abstractions 내의 구현을 최소한으로 유지하고, 동적 방법론 또는 사용자 지정 방법론을 위한 충분한 여지를 남깁니다.

function resolvePrecept(interfaceName) {
    var interfaceName = interfaceName;
    return function curry(value) {
        /*      throw new Error(interfaceName + ' requires an implementation for ...');     */
        console.warn('%s requires an implementation for ...', interfaceName);
        return value;
    };
}

var iAbstractClass = function AbstractClass() {
    var defaultTo = resolvePrecept('iAbstractClass');

    this.datum1 = this.datum1 || defaultTo(new Number());
    this.datum2 = this.datum2 || defaultTo(new String());

    this.method1 = this.method1 || defaultTo(new Function('return new Boolean();'));
    this.method2 = this.method2 || defaultTo(new Function('return new Object();'));

};

var ConcreteImplementation = function ConcreteImplementation() {

    this.datum1 = 1;
    this.datum2 = 'str';

    this.method1 = function method1() {
        return true;
    };
    this.method2 = function method2() {
        return {};
    };

    //Applies Interface (Implement iAbstractClass Interface)
    iAbstractClass.apply(this);  // .call / .apply after precept definitions
};

참가자

프리셉트 리졸바

resolvePrecept함수는 Abstract 클래스 내에서 사용하는 유틸리티 및 도우미 함수입니다.캡슐화된 프리셉트(데이터 동작)의 커스터마이즈된 실장 처리를 가능하게 합니다.오류를 발생시키거나 기본값을 Implementor 클래스에 할당할 수 있습니다.

iAbstract Class

iAbstractClass에 사용하는 인터페이스를 정의합니다.그 접근방식은 실행자 클래스와의 암묵적인 합의를 수반한다.이 인터페이스는 각 프리셉트를 동일한 프리셉트 이름 공간(OR)에 프리셉트 해결기 함수가 반환하는 모든 것에 할당합니다.단, 암묵적인 합의는 컨텍스트(Implementor의 제공) 해결됩니다.

실장자

구현자는 인터페이스(이 경우 iAbstractClass)에 단순히 동의하고 컨스트럭터-Hijacking을 사용하여 적용합니다.iAbstractClass.apply(this)위의 데이터와 동작을 정의하고 인터페이스 컨스트럭터를 하이잭(Implementor의 컨텍스트를 Interface 컨스트럭터에 전달)함으로써 Implementor의 오버라이드가 추가되고 인터페이스가 경고와 디폴트값을 설명할 수 있습니다.

이것은 오랜 시간 동안, 그리고 다른 프로젝트에서도 저와 제 팀에게 매우 도움이 된 매우 귀찮은 접근법입니다.단, 몇 가지 주의사항과 단점이 있습니다.

결점

이것은 소프트웨어 전체에 걸쳐 일관성을 구현하는 데 큰 도움이 되지만, 진정한 인터페이스구현하는 것이 아니라 에뮬레이트합니다.정의, 기본값, 경고 또는 오류에 대해 설명하지만 사용 설명은 개발자에 의해 강제되고 주장됩니다(JavaScript 개발의 많은 부분과 마찬가지로).

이것이 "JavaScript의 인터페이스"에 대한 최선의 접근법이라고 생각됩니다만, 다음과 같은 문제를 해결했으면 합니다.

  • 반환 유형의 어설션
  • 시그니처의 아사션
  • freeze브 の freeze from from 。delete
  • JavaScript 커뮤니티에 널리 보급되어 있거나 필요한 기타 사항의 어설션

그렇긴 하지만, 저와 제 팀이 함께 하는 만큼 당신에게도 도움이 되길 바랍니다.

호프, 아직도 답을 찾고 있는 사람은 그게 도움이 될 거야

Proxy (ECMAScript 2015부터 표준)를 사용해 볼 수 있습니다.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

latLngLiteral = new Proxy({},{
    set: function(obj, prop, val) {
        //only these two properties can be set
        if(['lng','lat'].indexOf(prop) == -1) {
            throw new ReferenceError('Key must be "lat" or "lng"!');
        }

        //the dec format only accepts numbers
        if(typeof val !== 'number') {
            throw new TypeError('Value must be numeric');
        }

        //latitude is in range between 0 and 90
        if(prop == 'lat'  && !(0 < val && val < 90)) {
            throw new RangeError('Position is out of range!');
        }
        //longitude is in range between 0 and 180
        else if(prop == 'lng' && !(0 < val && val < 180)) {
            throw new RangeError('Position is out of range!');
        }

        obj[prop] = val;

        return true;
    }
});

그러면 다음과 같이 쉽게 말할 수 있습니다.

myMap = {}
myMap.position = latLngLiteral;

instanceof(@) 할 수 (@Kamaffeather) 。

class LatLngLiteral {
    constructor(props)
    {
        this.proxy = new Proxy(this, {
            set: function(obj, prop, val) {
                //only these two properties can be set
                if(['lng','lat'].indexOf(prop) == -1) {
                    throw new ReferenceError('Key must be "lat" or "lng"!');
                }

                //the dec format only accepts numbers
                if(typeof val !== 'number') {
                    throw new TypeError('Value must be numeric');
                }

                //latitude is in range between 0 and 90
                if(prop == 'lat'  && !(0 < val && val < 90)) {
                    throw new RangeError('Position is out of range!');
                }
                //longitude is in range between 0 and 180
                else if(prop == 'lng' && !(0 < val && val < 180)) {
                    throw new RangeError('Position is out of range!');
                }

                obj[prop] = val;

                return true;
            }
        })
        return this.proxy
    }
}

'아까', '아까', '아까', '아까', '아까'를 사용하지 않고 할 수 있어요.Proxy대신 클래스는 getterssetters:

class LatLngLiteral {
    #latitude;
    #longitude;

    get lat()
    {
        return this.#latitude;
    }

    get lng()
    {
        return this.#longitude;
    }
    
    set lat(val)
    {
        //the dec format only accepts numbers
        if(typeof val !== 'number') {
            throw new TypeError('Value must be numeric');
        }

        //latitude is in range between 0 and 90
        if(!(0 < val && val < 90)) {
            throw new RangeError('Position is out of range!');
        }
        
        this.#latitude = val
    }
    
    set lng(val)
    {
        //the dec format only accepts numbers
        if(typeof val !== 'number') {
            throw new TypeError('Value must be numeric');
        }

        //longitude is in range between 0 and 180
        if(!(0 < val && val < 180)) {
            throw new RangeError('Position is out of range!');
        }
        
        this.#longitude = val
    }
}

이와 같은 추상적인 인터페이스

const MyInterface = {
  serialize: () => {throw "must implement serialize for MyInterface types"},
  print: () => console.log(this.serialize())
}

인스턴스를 만듭니다.

function MyType() {
  this.serialize = () => "serialized "
}
MyType.prototype = MyInterface

그것을 사용하다

let x = new MyType()
x.print()

Java 의 인터페이스는 정적으로 입력되어 컴파일 중에 클래스 간의 계약을 알 수 있어야 하기 때문에 필요합니다.JavaScript에서는 다릅니다.JavaScript는 동적으로 입력됩니다.즉, 객체를 취득했을 때 특정 메서드가 있는지 확인하고 호출할 수 있습니다.

트랜스 컴파일러를 사용하고 싶은 경우는, TypeScript 를 사용해 주세요.cofefeescript 또는 babel과 같은 언어와 유사한 ECMA 초안 기능(제안에서는 인터페이스를 "프로토콜"이라고 부릅니다)을 지원합니다.

TypeScript에서 인터페이스는 다음과 같습니다.

interface IMyInterface {
    id: number; // TypeScript types are lowercase
    name: string;
    callback: (key: string; value: any; array: string[]) => void;
    type: "test" | "notATest"; // so called "union type"
}

할 수 없는 일:

JavaScript에는 네이티브 인터페이스가 없습니다.인터페이스를 시뮬레이트 하는 방법은 여러 가지가 있습니다.나는 그것을 하는 소포를 썼다.

여기 이식을 볼 수 있습니다.

Javascript에는 인터페이스가 없습니다.그러나 오리형일 수 있습니다. 예를 들어 다음과 같습니다.

http://reinsbrain.blogspot.com/2008/10/interface-in-javascript.html

이것은 오래된 질문이지만, 그럼에도 불구하고 이 주제는 나를 끊임없이 괴롭힌다.

여기와 웹상의 많은 답변이 인터페이스를 "강제화"하는 데 중점을 두고 있기 때문에 다른 관점을 제안하고 싶습니다.

같은 동작을 하는 복수의 클래스(, 인터페이스의 실장)를 사용하고 있는 경우에, 인터페이스의 부족을 가장 많이 느낍니다.

예를 들어, Email Sections Factory를 수신할 것으로 예상되는 Email Generator가 있습니다. Email Sections Factory는 섹션의 콘텐츠와 HTML을 생성하는 방법을 "알고" 있습니다.따라서 모두 어떤 종류의 E-메일 생성기가 필요합니다.getContent(id) ★★★★★★★★★★★★★★★★★」getHtml(content)★★★★★★★★★★★★★★★★★★.

인터페이스에 가장 가까운 패턴(아직 회피책이지만)은 2개의 인수를 얻을 수 있는 클래스를 사용하는 것입니다.이 클래스는 2개의 인터페이스 메서드를 정의합니다.

큰 이 둘 중 입니다.static또는 인스턴스 자체를 인수로서 취득해, 그 속성에 액세스 합니다.그러나 이 트레이드오프가 번거롭게 할 가치가 있다고 생각하는 경우가 있습니다.

class Filterable {
  constructor(data, { filter, toString }) {
    this.data = data;
    this.filter = filter;
    this.toString = toString;
    // You can also enforce here an Iterable interface, for example,
    // which feels much more natural than having an external check
  }
}

const evenNumbersList = new Filterable(
  [1, 2, 3, 4, 5, 6], {
    filter: (lst) => {
      const evenElements = lst.data.filter(x => x % 2 === 0);
      lst.data = evenElements;
    },
    toString: lst => `< ${lst.data.toString()} >`,
  }
);

console.log('The whole list:    ', evenNumbersList.toString(evenNumbersList));
evenNumbersList.filter(evenNumbersList);
console.log('The filtered list: ', evenNumbersList.toString(evenNumbersList));

오래된 API인 것은 알지만, 최근 인터페이스에 대한 오브젝트를 체크하기 위한 편리한 API가 점점 더 필요하게 되었습니다.그래서 이렇게 썼습니다.https://github.com/tomhicks/methodical

NPM을하실 수 npm install methodical

것을 할 수 있으며, 모두 됩니다.if (typeof x.method === 'function')보일러 플레이트

누군가 유용하게 썼으면 좋겠네요.

오래된 것이지만 트랜스필러 없이 ES6에서 사용할 인터페이스를 구현했습니다.

https://github.com/jkutianski/ES6-Interfaces

인터페이스를 사용하면 다형성을 구현할 수 있습니다.Javascript는 이것과 다른 것을 처리하기 위해 인터페이스 유형이 필요하지 않습니다.interface.메서드가 같은 클래스의 배열을 예로 들어 보겠습니다.

Circle()
Square()
Triangle()

다형성이 어떻게 작용하는지 알고 싶다면 데이비드 크루글린스키의 Book MFC가 좋다(C++용으로 작성됨).

에서는, 을 실시합니다.draw() 내의 하고, 「」를 합니다.draw()루프의 메서드를 사용하여 배열을 반복합니다.그건 완전히 유효합니다.했다고 할 수.abstract class현실에는 없지만, 당신은 그것을 했고, Javascript는 아무런 문제가 없습니다.실제 인터페이스와의 차이점은 모든 인터페이스 방식을 구현해야 한다는 것입니다.이 경우 필요하지 않습니다.

인터페이스는 계약입니다.모든 방법을 실행해야 합니다.정적으로 하는 것만으로, 그것을 할 수 있습니다.

Javascript와 같은 언어를 다이내믹에서 스태틱으로 변경하는 것은 의문입니다.정적인 것은 개선되지 않습니다.경험 많은 개발자는 Javascript의 동적 특성에 문제가 없습니다.

그래서 나는 타이프스크립트를 사용하는 이유가 명확하지 않다.노드를 사용하는 경우JS는 Javascript와 함께 매우 효율적이고 비용 효율적인 엔터프라이즈 웹 사이트를 구축할 수 있습니다.Javascript/NodeJS/MongoDB 조합은 이미 훌륭한 승자입니다.

이것을 시험해 보세요.하고, 「」를 사용합니다.@implementsJSDoc: 특정 클래스에 정의된 인터페이스가 구현되어 있음을 나타냅니다.일부 속성이 구현되지 않은 경우 클래스 이름에 빨간색 꼬불꼬불한 줄이 표시됩니다.VSCode를 사용하다

// @ts-check

// describe interface using a class
class PlainInterface {
    size = 4;
    describe() {}
    show(){ }
}

/**
 * @implements  PlainInterface 
 */
class ConcretePlain {
    size = 4;
    describe() {
        console.log('I am described')
    }
    show(){
        console.log('I am shown')
    }
}       

const conc = new ConcretePlain();
conc.describe();

또, 가능한 한 임팩트가 적은 인터페이스를 모방하는 솔루션을 찾는 것도 귀찮았습니다.

한 가지 해결책은 도구를 만드는 것입니다.

/**
@parameter {Array|object} required : method name list or members types by their name
@constructor
*/
let Interface=function(required){
    this.obj=0;
    if(required instanceof Array){
        this.obj={};
        required.forEach(r=>this.obj[r]='function');
    }else if(typeof(required)==='object'){
        this.obj=required;
    }else {
        throw('Interface invalid parameter required = '+required);
    }
};
/** check constructor instance
@parameter {object} scope : instance to check.
@parameter {boolean} [strict] : if true -> throw an error if errors ar found.
@constructor
*/
Interface.prototype.check=function(scope,strict){
    let err=[],type,res={};
    for(let k in this.obj){
        type=typeof(scope[k]);
        if(type!==this.obj[k]){
            err.push({
                key:k,
                type:this.obj[k],
                inputType:type,
                msg:type==='undefined'?'missing element':'bad element type "'+type+'"'
            });
        }
    }
    res.success=!err.length;
    if(err.length){
        res.msg='Class bad structure :';
        res.errors=err;
        if(strict){
            let stk = new Error().stack.split('\n');
            stk.shift();
            throw(['',res.msg,
                res.errors.map(e=>'- {'+e.type+'} '+e.key+' : '+e.msg).join('\n'),
                '','at :\n\t'+stk.join('\n\t')
            ].join('\n'));

        }
    }
    return res;
};

사용 예:

// create interface tool
let dataInterface=new Interface(['toData','fromData']);
// abstract constructor
let AbstractData=function(){
    dataInterface.check(this,1);// check extended element
};
// extended constructor
let DataXY=function(){
    AbstractData.apply(this,[]);
    this.xy=[0,0];
};
DataXY.prototype.toData=function(){
    return [this.xy[0],this.xy[1]];
};

// should throw an error because 'fromData' is missing
let dx=new DataXY();

수업 포함

class AbstractData{
    constructor(){
        dataInterface.check(this,1);
    }
}
class DataXY extends AbstractData{
    constructor(){
        super();
        this.xy=[0,0];
    }
    toData(){
        return [this.xy[0],this.xy[1]];
    }
}

아직 비트의 퍼포먼스를 소비하고 있어 인터페이스 클래스에 의존해야 하지만 debug 또는 open api에 사용할 수 있습니다.

Js에는 인터페이스가 없지만 typescript에는 인터페이스가 있습니다!

자바스크립트에는 인터페이스가 없지만 이 메시지 아래에 있는 코드로 동작을 조금 흉내낼 수 있습니다.인터페이스는 기본적으로 강제된 계약이기 때문에 직접 구축할 수 있습니다.

아래 코드는 인터페이스, 부모 및 자녀 클래스의 3가지 클래스 중 존재합니다.

  • 인터페이스에는 필요한 메서드와 속성이 존재하는지 여부를 확인하는 메서드가 있습니다.

  • [부모(Parent)]는 [인터페이스(Interface)]클래스를 사용하여 자녀에게 필요한 메서드와 속성을 적용하는 데 사용됩니다.

  • 자녀는 부모 규칙이 적용되는 클래스입니다.

올바르게 설정한 후 하위 항목에 메서드 또는 속성이 없으면 콘솔에 오류가 표시되고 하위 항목이 올바르게 계약을 구현하면 아무것도 표시되지 않습니다.

class Interface {  
    checkRequiredMethods(methodNames) {
        setTimeout( () => {
            const loopLength = methodNames.length;
            let i = 0
            for (i; i<loopLength; i++) {
                if (typeof this[methodNames[i]] === "undefined") {
                    this.throwMissingMethod(methodNames[i]);
                }

                else if (typeof this[methodNames[i]] !== "function") {
                    this.throwNotAMethod(methodNames[i]);
                }
            }
        }, 0);
    }

    checkRequiredProperties(propNames) {
        setTimeout( () => {
            const loopLength = propNames.length;
            let i = 0
            for (i; i<loopLength; i++) {
                if (typeof this[propNames[i]] === "undefined") {
                    this.throwMissingProperty(propNames[i]);
                }

                else if (typeof this[propNames[i]] === "function") {
                    this.throwPropertyIsMethod(propNames[i]);
                }
            }
        }, 0);     
    }

    throwMissingMethod(methodName) {
        throw new Error(`error method ${methodName} is undefined`);
    }

    throwNotAMethod(methodName) {
        throw new Error(`error method ${methodName} is not a method`);
    }

    throwMissingProperty(propName) {
        throw new Error(`error property ${propName} is not defined`);
    }

    throwPropertyIsMethod(propName) {
        throw new Error(`error property ${propName} is a method`);
    }
}
class Parent extends Interface {
    constructor() {
        super()

        this.checkRequiredProperties([
            "p1",
            "p2",
            "p3",
            "p4",
            "p5"
        ]);

        this.checkRequiredMethods([ 
            "m1",
            "m2",
            "m3",
            "m4"
        ]);
    }
}
class Child extends Parent {
    p1 = 0;
    p2 = "";
    p3 = false;
    p4 = [];
    p5 = {};

    constructor() {
        super();
    }

    m1() {}
    m2() {}
    m3() {}
    m4() {}
}
new Child()

아니요, 하지만 믹스인이 있어요.Abstract 서브클래스 또는 mixins를 대체 수단으로 사용할 수 있습니다.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#mix-ins

언급URL : https://stackoverflow.com/questions/3710275/does-javascript-have-the-interface-type-such-as-javas-interface

반응형