Class basic syntax
Wikipedia
class User {
constructor(name) {
this.name = name;
}
sayHi() {
console.log(this.name);
}
}
// Usage:
let user = new User("John");
user.sayHi();
What is a class?
// proof: User is a function
// 证明: User是一个函数
console.log(typeof User); // function
class User {
constructor(name) {
this.name = name;
}
sayHi() {
console.log(this.name);
}
}
// class is a function
console.log(typeof User);
// ...or, more precisely, the constructor method
// more precisely 更确切地说
console.log(User === User.prototype.constructor); // true
// The methods are in User.prototype, e.g:
// 方法在User.prototype中
console.log(User.prototype.sayHi); // console.log(this.name);
// there are exactly two methods in the prototype
// 原型中有两种方法
console.log(Object.getOwnPropertyNames(User.prototype)); // constructor, sayHi
Not just a syntactic sugar
// rewriting class User in pure functions
// 用纯函数重写类User
// 1. Create constructor function
function User(name) {
this.name = name;
}
// a function prototype has "constructor" property by default,
// so we don't need to create it
// 函数原型默认具有“构造函数”属性,所以我们不需要创建它
// 2. Add the method to prototype
User.prototype.sayHi = function() {
console.log(this.name);
};
// Usage:
let user = new User("John");
user.sayHi();
Class Expression
Getters/Setters
Computed names [...]
Class Fields
Making bound methods with class fields
Summary
Tasks
Rewrite to class
function Clock({ template }) {
let timer;
function render() {
let date = new Date();
let hours = date.getHours();
if (hours < 10) hours = "0" + hours;
let mins = date.getMinutes();
if (mins < 10) mins = "0" + mins;
let secs = date.getSeconds();
if (secs < 10) secs = "0" + secs;
let output = template
.replace("h", hours)
.replace("m", mins)
.replace("s", secs);
console.log(output);
}
this.stop = function() {
clearInterval(timer);
};
this.start = function() {
render();
timer = setInterval(render, 1000);
};
}
let clock = new Clock({ template: "h:m:s" });
clock.start();
class Clock {
constructor({ template }) {
this.template = template;
}
render() {
let date = new Date();
let hours = date.getHours();
if (hours < 10) hours = "0" + hours;
let mins = date.getMinutes();
if (mins < 10) mins = "0" + mins;
let secs = date.getSeconds();
if (secs < 10) secs = "0" + secs;
let output = this.template
.replace("h", hours)
.replace("m", mins)
.replace("s", secs);
console.log(output);
}
stop() {
clearInterval(this.timer);
}
start() {
this.render();
this.timer = setInterval(() => this.render(), 1000);
}
}
let clock = new Clock({ template: "h:m:s" });
clock.start();