在ES6中创建多个构造函数 [英] Creating multiple constructor in ES6

查看:67
本文介绍了在ES6中创建多个构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ES5中,可以为一个类创建多个构造函数,同时使用原型保留两者的共同部分,如下所示

In ES5 it was possible to create multiple constructors for a class while keeping common parts to both using prototypes, as shown below

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类和构造函数语法实现相同的结果

I want to achieve the same result using ES6 class and constructor syntax

class Book{
    constructore (){}
}

推荐答案

ECMAScript不支持函数/构造函数重载.如果您仍想修改它,则可以使用arguments对象来实现.

Function/constructor overloading is not supported in ECMAScript. You can use the arguments object to do so if you want to still hack it.

constructor(title, length, author) {
        if(!arguments.length) {
            // empty book
        }
        else {
            this.title = title;
            this.Length = length;
            this.author = author;
        }
    }

这篇关于在ES6中创建多个构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆