IT

여러 생성 기능을위한 JavaScript 패턴

lottoking 2020. 8. 30. 09:05
반응형

여러 생성 기능을위한 JavaScript 패턴


내 인스턴스에 대해 다른 생성자가 필요합니다. 어떤 일반적인 일반적인 패턴은 무엇입니까?


JavaScript는 메소드 또는 생성 능력을 포함하여 함수 오버로딩이 없습니다.

전달하는 매개 변수의 수와 유형에 따라 함수가 다르게 작동하도록 수동으로 스니핑해야합니다. JavaScript는 선언 된 인수 수보다 많거나 약간 함수를 기꺼이 호출합니다.

function foo(a, b) {
    if (b===undefined) // parameter was omitted in call
        b= 'some default value';

    if (typeof(a)==='string')
        this._constructInSomeWay(a, b);
    else if (a instanceof MyType)
        this._constructInSomeOtherWay(a, b);
}

arguments추가 인수를 전달하기 위해 배열과 방식 방식으로 액세스 할 수도 있습니다 .

더 복잡한 인수가 필요한 경우 일부 또는 구비하는 것이 좋습니다.

function bar(argmap) {
    if ('optionalparam' in argmap)
        this._constructInSomeWay(argmap.param, argmap.optionalparam);
    ...
}

bar({param: 1, optionalparam: 2})

Python은 기본 및 명명 된 인수를 사용하여 함수로 더 실용적이고 우아한 방식으로 대부분의 사용 사례를 처리하는 방법을 보여줍니다. JavaScript는 그다지 많지 않습니다.


이걸 어떻게 찾나요?

function Foobar(foobar) {
    this.foobar = foobar;
}

Foobar.prototype = {
    foobar: null
};

Foobar.fromComponents = function(foo, bar) {
    var foobar = foo + bar;
    return new this(foobar);
};

bobince의 답변처럼 손으로하고 갑자기 갑자기 기 때문에 jQuery의 플러그인 패턴을 완전히 제거했습니다.

생성자는 다음과 같습니다.

//default constructor for Preset 'class'
function Preset(params) {
    var properties = $.extend({
        //these are the defaults
        id: null,
        name: null,
        inItems: [],
        outItems: [],
    }, params);

    console.log('Preset instantiated');
    this.id = properties.id;
    this.name = properties.name;
    this.inItems = properties.inItems;
    this.outItems = properties.outItems;
}

다음은 다양한 인스턴스화 방법입니다.

presetNoParams = new Preset(); 
presetEmptyParams = new Preset({});
presetSomeParams = new Preset({id: 666, inItems:['item_1', 'item_2']});
presetAllParams = new Preset({id: 666, name: 'SOpreset', inItems: ['item_1', 'item_2'], outItems: ['item_3', 'item_4']});

그 결과는 다음과 가변적입니다.

presetNoParams
Preset {id: null, name: null, inItems: Array[0], outItems: Array[0]}

presetEmptyParams
Preset {id: null, name: null, inItems: Array[0], outItems: Array[0]}

presetSomeParams
Preset {id: 666, name: null, inItems: Array[2], outItems: Array[0]}

presetAllParams
Preset {id: 666, name: "SOpreset", inItems: Array[2], outItems: Array[2]}


eruciform의 답변으로 더 나아가면 new호출을 메소드 init수 있습니다 .

function Foo () {
    this.bar = 'baz';
}

Foo.prototype.init_1 = function (bar) {
    this.bar = bar;
    return this;
};

Foo.prototype.init_2 = function (baz) {
    this.bar = 'something to do with '+baz;
    return this;
};

var a = new Foo().init_1('constructor 1');
var b = new Foo().init_2('constructor 2');

여러 매개 변수의 많은 충분한 생성자에 있습니다. 그리고 이것은 대부분의 생성자 기능을 사용할 때 호출되는 init (other-params)입니다. 또한 팩토리 개념을 사용하여 원하는 다른 개체를 만들 수있는 개체를 만드는 것을 고려하십시오.

http://en.wikipedia.org/w/index.php?title=Factory_method_pattern&oldid=363482142#Javascript


해당 클래스의 인스턴스를 반환하는 정적 메서드와 함께 클래스를 사용할 수 있습니다.

    class MyClass {
        constructor(a,b,c,d){
            this.a = a
            this.b = b
            this.c = c
            this.d = d
        }
        static BAndCInstance(b,c){
            return new MyClass(null,b,c)
        }
        static BAndDInstance(b,d){
            return new MyClass(null,b, null,d)
        }
    }

    //new Instance just with a and other is nul this can
    //use for other params that are first in constructor
    const myclass=new MyClass(a)

    //an Instance that has b and c params
    const instanceWithBAndC = MyClass.BAndCInstance(b,c)

    //another example for b and d
    const instanceWithBAndD = MyClass.BAndDInstance(b,d)

이 패턴을 사용하면 다중 생성자를 만들 수 있습니다.


이것은 JavaScript 및 CSS3-Exam Ref를 사용한 HTML5 프로그래밍의 여러 생성자에 대해 제공된 예제 입니다.

function Book() {
    //just creates an empty book.
}


function Book(title, length, author) {
    this.title = title;
    this.Length = length;
    this.author = author;
}

Book.prototype = {
    ISBN: "",
    Length: -1,
    genre: "",
    covering: "",
    author: "",
    currentPage: 0,
    title: "",

    flipTo: function FlipToAPage(pNum) {
        this.currentPage = pNum;
    },

    turnPageForward: function turnForward() {
        this.flipTo(this.currentPage++);
    },

    turnPageBackward: function turnBackward() {
        this.flipTo(this.currentPage--);
    }
};

var books = new Array(new Book(), new Book("First Edition", 350, "Random"));

참고 URL : https://stackoverflow.com/questions/3220721/javascript-pattern-for-multiple-constructors

반응형