JavaScript pattern for multiple constructors

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

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

9条回答
  •  广开言路
    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"));
    

提交回复
热议问题