JavaScript pattern for multiple constructors

前端 未结 9 950
不知归路
不知归路 2020-12-07 13:12

I need different constructors for my instances. What is a common pattern for that?

相关标签:
9条回答
  • 2020-12-07 13:34

    you can use class with static methods that return an instance of that class

        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)
    

    with this pattern you can create multi constructor

    0 讨论(0)
  • 2020-12-07 13:39

    Sometimes, default values for parameters is enough for multiple constructors. And when that doesn't suffice, I try to wrap most of the constructor functionality into an init(other-params) function that is called afterwards. Also consider using the factory concept to make an object that can effectively create the other objects you want.

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

    0 讨论(0)
  • 2020-12-07 13:41

    This is the example given for multiple constructors in Programming in HTML5 with JavaScript and CSS3 - Exam Ref.

    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"));
    
    0 讨论(0)
提交回复
热议问题