在传统的写对象模板的方式是这样的
function oldModel(){
constructor(){
this.name = '';
}
}
oldModel.prototype.method=function(){
}
而ES6的class语法糖
class newModel {
constructor(){
this.name='';
}
method(){
}
}
整体使用上更简约,代码量也更少。
在class内部,还有static的静态方法,查找资料和学习了下
类(class)通过 static 关键字定义静态方法。不能在类的实例上调用静态方法,而应该通过类本身调用。这些通常是实用程序方法,例如创建或克隆对象的功能。
class StaticMethodCall {
constructor(){
this.name1='1111';
}
static staticMethod() {
return 'Static method has been called';
}
static anotherStaticMethod() {
// 静态方法调用同一个类中的其他静态方法,可使用this关键字
return this.staticMethod() + ' from another static method';
}
method(){
return 'method';
}
}
console.log(StaticMethodCall.staticMethod());
// 'Static method has been called'
console.log(StaticMethodCall.anotherStaticMethod());
// 'Static method has been called from another static method
var s = new StaticMethodCall();
s.staticMethod() // 报错,s.staticMethod is not a function
s.method() // 'method'
从类的构造函数里使用,需要类名来调用或者用类构造函数的属性来调用该方法
class StaticMethodCall {
constructor() {
console.log(StaticMethodCall.staticMethod());
// 'static method has been called.'
console.log(this.constructor.staticMethod());
// 'static method has been called.'
}
static staticMethod() {
return 'static method has been called.';
}
}
资料采摘:https://blog.csdn.net/qq_38045106/article/details/84666638