代码之家  ›  专栏  ›  技术社区  ›  Varun Sukheja

在ES6中创建多个构造函数

  •  0
  • Varun Sukheja  · 技术社区  · 6 年前

    在ES5中,可以为一个类创建多个构造器,同时使用原型将公共部分同时保留给这两个部分,如下所示

    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"));
    

    我想使用ES6类和构造函数语法获得相同的结果

    class Book{
        constructore (){}
    }
    
    2 回复  |  直到 6 年前
        1
  •  3
  •   Saransh Kataria    6 年前

    ECMAScript不支持函数/构造函数重载。如果您还想破解arguments对象,可以使用它。

    constructor(title, length, author) {
            if(!arguments.length) {
                // empty book
            }
            else {
                this.title = title;
                this.Length = length;
                this.author = author;
            }
        }
    
        2
  •  0
  •   Aadit M Shah    6 年前

    实际上,确实可以为一个原型创建多个构造函数。你只要看看 constructor 原型的属性 is not special . 因此,可以创建多个构造函数,如下所示:

    const type = (prototype, constructor) =>
        (constructor.prototype = prototype, constructor);
    
    const book = {
        flipTo(page) {
            this.page = page;
        },
        turnPageForward() {
            this.page++;
        },
        turnPageBackward() {
            this.page--;
        }
    };
    
    const EmptyBook = type(book, function EmptyBook() {
        this.constructor = EmptyBook;
        this.ISBN        = "";
        this.title       = "";
        this.author      = "";
        this.genre       = "";
        this.covering    = "";
        this.length      = -1;
        this.page        = 0;
    });
    
    const Book = type(book, function Book(title, author, length) {
        this.constructor = Book;
        this.ISBN        = "";
        this.title       = title;
        this.author      = author;
        this.genre       = "";
        this.covering    = "";
        this.length      = length;
        this.page        = 0;
    });
    

    只需给构造函数起不同的名字。希望能有所帮助。