Var*_*eja 2 javascript ecmascript-6 es6-class
在 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"));
Run Code Online (Sandbox Code Playgroud)
我想使用 ES6 类和构造函数语法实现相同的结果
class Book{
constructore (){}
}
Run Code Online (Sandbox Code Playgroud)
小智 8
ECMAScript 不支持函数/构造函数重载。如果你仍然想破解它,你可以使用参数对象来做到这一点。
constructor(title, length, author) {
if(!arguments.length) {
// empty book
}
else {
this.title = title;
this.Length = length;
this.author = author;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5703 次 |
| 最近记录: |