>  기사  >  웹 프론트엔드  >  효과적인 JavaScript 항목 55 구성 개체를 함수 매개 변수로 허용

효과적인 JavaScript 항목 55 구성 개체를 함수 매개 변수로 허용

高洛峰
高洛峰원래의
2016-11-25 09:18:171210검색

함수가 허용하는 매개변수의 순서를 유지하는 것이 중요하지만, 함수가 허용할 수 있는 매개변수의 수가 특정 수에 도달하면 사용자에게도 골치 아픈 일이 됩니다.

var alert = new Alert(100, 75, 300, 200,
    "Error", message,
    "blue", "white", "black",
    "error", true);

함수가 계속해서 재구성되고 발전함에 따라 수용할 수 있는 매개변수가 점점 더 많아질 수 있으며 결국 위의 예와 같습니다.

이 경우 JavaScript는 구성 개체를 사용하여 위의 모든 매개변수를 대체할 수 있습니다.

var alert = new Alert({
    x: 100, y: 75,
    width: 300, height: 200,
    title: "Error", message: message,
    titleColor: "blue", bgColor: "white", textColor: "black",
    icon: "error", modal: true});

이렇게 하면 코드가 좀 더 장황해지기는 하지만, 이점은 분명합니다. 구성 개체의 각 속성 이름은 사용자에게 이 속성의 용도를 알려주는 문서와 같습니다. 특히 부울 값의 경우 참과 거짓만을 전달하여 진정한 의도를 판단하기가 어렵습니다.

이 접근 방식을 사용할 때의 또 다른 이점은 모든 속성이 선택 사항이라는 것입니다. 구성 개체에 속성이 나타나지 않으면 기본값이 대신 사용됩니다.

var alert = new Alert(); // use all default parameter values

함수가 필수 매개변수를 허용해야 하는 경우 다음과 같이 구성 개체 외부에 배치하는 것이 가장 좋습니다.

var alert = new Alert(app, message, {
    width: 150, height: 100,
    title: "Error",
    titleColor: "blue", bgColor: "white", textColor: "black",
    icon: "error", modal: true});

구성 개체의 모든 속성은 다음과 같습니다. 함수가 허용할 수 있는 모든 선택적 매개변수인 반면, 앱과 메시지는 전달되어야 하는 매개변수입니다.

구성 개체를 처리하려면 다음과 같이 할 수 있습니다.

function Alert(parent, message, opts) {
    opts = opts || {}; // default to an empty options object
    this.width = opts.width === undefined ? 320 : opts.width;
    this.height = opts.height === undefined
                ? 240
                : opts.height;
    this.x = opts.x === undefined
            ? (parent.width / 2) - (this.width / 2)
            : opts.x;
    this.y = opts.y === undefined
            ? (parent.height / 2) - (this.height / 2)
            : opts.y;
    this.title = opts.title || "Alert";
    this.titleColor = opts.titleColor || "gray";
    this.bgColor = opts.bgColor || "white";
    this.textColor = opts.textColor || "black";
    this.icon = opts.icon || "info";
    this.modal = !!opts.modal;
    this.message = message;
}

선택적 구성 개체의 경우 진리값에서 false를 반환하는 경우 먼저 항목 54에 소개된 방법을 사용합니다. 판단, 빈 객체로 교체하세요.

위 코드에는 개체 확장이나 병합 기능을 사용하여 추가로 최적화할 여지가 있습니다. 많은 JavaScript 라이브러리 및 프레임워크에는 대상 개체와 소스 개체를 허용한 다음 소스 개체의 속성을 대상 개체에 복사하는 확장 기능이 있습니다.

function Alert(parent, message, opts) {
    opts = extend({
        width: 320,
        height: 240
    });
    opts = extend({
        x: (parent.width / 2) - (opts.width / 2),
        y: (parent.height / 2) - (opts.height / 2),
        title: "Alert",
        titleColor: "gray",
        bgColor: "white",
        textColor: "black",
        icon: "info",
        modal: false
    }, opts);    this.width = opts.width;    this.height = opts.height;    this.x = opts.x;    this.y = opts.y;    this.title = opts.title;    this.titleColor = opts.titleColor;    this.bgColor = opts.bgColor;    this.textColor = opts.textColor;    this.icon = opts.icon;    this.modal = opts.modal;
}

확장 기능을 통해, 더 이상 각 속성을 지속적으로 판단할 필요가 없습니다. 위 코드의 첫 번째 확장 함수는 너비와 높이 속성이 설정되지 않은 경우 기본값을 설정하는 데 사용됩니다. 두 번째 확장 함수에서는 이를 기반으로 계산되기 때문입니다.

결국 모든 속성이 이 개체에 할당되면 위 코드는 다음과 같이 단순화될 수 있습니다.

function Alert(parent, message, opts) {
    opts = extend({
        width: 320,
        height: 240
    });
    opts = extend({
        x: (parent.width / 2) - (opts.width / 2),
        y: (parent.height / 2) - (opts.height / 2),
        title: "Alert",
        titleColor: "gray",
        bgColor: "white",
        textColor: "black",
        icon: "info",
        modal: false
    }, opts);
    extend(this, opts);
}

확장 함수의 구현은 일반적으로 소스 개체의 속성을 순회합니다. , 속성 값이 정의되지 않은 경우 대상 개체에 복사됩니다.

function extend(target, source) {
    if (source) {
        for (var key in source) {
            var val = source[key];
            if (typeof val !== "undefined") {
                target[key] = val;
            }
        }
    }
    return target;
}

요약

API를 더 쉽게 읽을 수 있도록 하려면 선택적 구성 개체를 사용하세요.

구성 매개변수의 속성은 함수의 선택적 매개변수여야 합니다.

확장 유틸리티 기능을 사용하면 구성 개체를 사용하는 코드를 단순화할 수 있습니다.


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.