ES6 的class可以看作只是一个ES5生成实例对象的构造函数的语法糖。它参考了java语言,定义了一个类的概念,让对象原型写法更加清晰,对象实例化更像是一种面向对象编程。Class类可以通过extends实现继承。它和ES5构造函数的不同点
类的内部定义的所有方法,都是不可枚举的
///ES5
function ES5Fun (x, y) {
this.x = x;
this.y = y;
}
ES5Fun.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
}
var p = new ES5Fun(1, 3);
p.toString();
Object.keys(ES5Fun.prototype); //['toString']
//ES6
class ES6Fun {
constructor (x, y) {
this.x = x;
this.y = y;
}
toString () {
return '(' + this.x + ', ' + this.y + ')';
}
}
Object.keys(ES6Fun.prototype); //[]
- ES6的class类必须用new命令操作,而ES5的构造函数不用new也可以执行。
- ES6的class类不存在变量提升,必须先定义class之后才能实例化,不像ES5中可以将构造函数写在实例化之后。
- ES5的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上面。ES6的继承机制完全不同,实质是先将父类实例对象的属性和方法,加到this上面(所以必须先调用super方法),然后再用子类的构造函数修改this。
class 声明创建一个基于原型继承的具有给定名称的新类。
class Polygon {
constructor(height, width) {
this.area = height * width;
}
}
console.log(new Polygon(4, 3).area);
// expected output: 12
在下面的例子中,我们首先定义一个名为Polygon的类,然后继承它来创建一个名为Square的类。注意,构造函数中使用的 super() 只能在构造函数中使用,并且必须在使用 this 关键字前调用。
class Polygon {
constructor(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
}
}
class Square extends Polygon {
constructor(length) {
super(length, length);
this.name = 'Square';
}
}
构造方法
constructor 是一种用于创建和初始化class创建的对象的特殊方法。
在一个类中只能有一个名为 “constructor” 的特殊方法。 一个类中出现多次构造函数 (constructor)方法将会抛出一个 SyntaxError 错误。
在一个构造方法中可以使用super关键字来调用一个父类的构造方法。
如果没有显式指定构造方法,则会添加默认的 constructor 方法。
如果不指定一个构造函数(constructor)方法, 则使用一个默认的构造函数(constructor)。
class Square extends Polygon {
constructor(length) {
// 在这里, 它调用了父类的构造函数, 并将 lengths 提供给 Polygon 的"width"和"height"
super(length, length);
// 注意: 在派生类中, 必须先调用 super() 才能使用 "this"。
// 忽略这个,将会导致一个引用错误。
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
// 注意:不可使用 this.area = value
// 否则会导致循环call setter方法导致爆栈
this._area = value;
}
}
extends
extends关键字用于类声明或者类表达式中,以创建一个类,该类是另一个类的子类。
class ChildClass extends ParentClass { … }
extends关键字用来创建一个普通类或者内建对象的子类。
继承的.prototype必须是一个Object 或者 null。
使用 extends与内置对象
class myDate extends Date {
constructor() {
super();
}
getFormattedDate() {
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
}
}
类私有域
class ClassWithPrivateField {
#privateField
}
class ClassWithPrivateMethod {
#privateMethod() {
return 'hello world'
}
}
class ClassWithPrivateStaticField {
static #PRIVATE_STATIC_FIELD
}
私有方法,私有静态方法
像它们的公有等价方法一样,私有静态方法是在类本身而非类的实例上调用的。 像私有静态字段一样,只能从类声明内部访问它们。
class ClassWithPrivateStaticMethod {
static #privateStaticMethod() {
return 42
}
static publicStaticMethod1() {
return ClassWithPrivateStaticMethod.#privateStaticMethod();
}
static publicStaticMethod2() {
return this.#privateStaticMethod();
}
}
assert(ClassWithPrivateStaticField.publicStaticMethod1() === 42);
assert(ClassWithPrivateStaticField.publicStaticMethod2() === 42);
综合实例
<body>
<input type="text" value="">
<button class="btn">一级废话</button>
<button class="btn2">二级废话</button>
<div></div>
<script>
const inp = document.querySelectorAll('input')[0]
const btn = document.querySelectorAll('.btn')[0]
const btn2 = document.querySelectorAll('.btn2')[0]
const div = document.querySelectorAll('div')[0]
class Bullshit {
static welcome_tips() {
return '温馨提示,给爷爬'
}
static welcome() {
div.innerHTML = this.welcome_tips()
}
constructor(text, color) {
this.text = text
this.color = color
}
show() {
div.innerHTML = this.text + '--' + this.text.split('').reverse().join('')
div.style.color = this.color
}
set extra(value) {
this.value = value
div.innerHTML += value
}
get extra() {
return `我是你爹啊:${this.value}`
}
}
btn.addEventListener('click', () => {
const bullshit = new Bullshit(inp.value, '#589c63')
bullshit.show()
bullshit.extra = 'baba'
})
class Son_of_Bullshit extends Bullshit {
constructor(text, color, fontSize) {
super(text, color)
this.fontSize = fontSize
}
show() {
div.style.fontSize = this.fontSize
div.innerHTML = this.text + '--' + this.text.split('').reverse().join('')
div.style.color = this.color
}
}
btn2.addEventListener('click', () => {
const bullshit = new Son_of_Bullshit(inp.value, '#f30f69', '32px')
bullshit.show()
bullshit.extra = 'yeye'
console.log(bullshit.extra);
})
div.addEventListener('click', () => {
Son_of_Bullshit.welcome()
})
</script>
</body>
参考文献:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes/static
参考视频:https://b23.tv/Lgx1Hq