Program Tip

RequireJS : 단일 "클래스"를 포함하는 모듈을 정의하는 방법은 무엇입니까?

programtip 2020. 11. 9. 20:33
반응형

RequireJS : 단일 "클래스"를 포함하는 모듈을 정의하는 방법은 무엇입니까?


각각 자체 JavaScript 파일에 구현 된 여러 JavaScript "클래스"가 있습니다. 개발을 위해 이러한 파일은 개별적으로로드되고 프로덕션을 위해 연결되지만 두 경우 모두로드 순서를 수동으로 정의하여 B가 A를 사용하는 경우 B가 A 뒤에 오도록 해야합니다. RequireJS 를 구현으로 사용할 계획 입니다. CommonJS Modules / AsynchronousDefinition 은 자동으로이 문제를 해결합니다.

각각 하나의 클래스를 내보내는 모듈을 정의하는 것보다 더 좋은 방법이 있습니까? 그렇지 않다면 모듈이 내보내는 이름을 어떻게 지정합니까? 아래 예제에서와 같이 "Employee"클래스를 내보내는 모듈 "employee"는 나에게 충분히 건조 하다고 느끼지 않습니다 .

define("employee", ["exports"], function(exports) {
    exports.Employee = function(first, last) {
        this.first = first;
        this.last = last;
    };
});

define("main", ["employee"], function (employee) {
    var john = new employee.Employee("John", "Smith");
});

AMD의 제안은 방금 내 보낸 개체에 대한 값을 반환 할 수 있습니다. 그러나 이는 AMD 제안의 기능이며 API 제안 일 뿐이며 모듈을 일반 CommonJS 모듈로 다시 변환하기가 더 어려워집니다. 괜찮다고 생각하지만 알아두면 유용한 정보입니다.

따라서 다음을 수행 할 수 있습니다.

생성자 함수를 내보내는 모듈이 대문자 이름으로 시작하는 것을 선호하므로이 모듈의 최적화되지 않은 버전도 Employee.js에 있습니다.

define("Employee", function () {
    //You can name this function here,
    //which can help in debuggers but
    //has no impact on the module name.
    return function Employee(first, last) {
        this.first = first; 
        this.last = last;
    };
});

이제 다른 모듈에서 다음과 같이 Employee 모듈을 사용할 수 있습니다.

define("main", ["Employee"], function (Employee) {
    var john = new Employee("John", "Smith");
});

jrburke의 답변 외에도 생성자 함수를 직접 반환 할 필요가 없습니다. 가장 유용한 클래스의 경우 프로토 타입을 통해 메서드를 추가 할 수도 있습니다. 다음과 같이 할 수 있습니다.

define('Employee', function() {
    // Start with the constructor
    function Employee(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    // Now add methods
    Employee.prototype.fullName = function() {
        return this.firstName + ' ' + this.lastName;
    };

    // etc.

    // And now return the constructor function
    return Employee;
});

실제로 이것은 requirejs.org에서이 예제에 표시된 패턴과 정확히 일치합니다 .

참고 URL : https://stackoverflow.com/questions/4869530/requirejs-how-to-define-modules-that-contain-a-single-class

반응형