ES6 class基本语法 及其 基本使用
一、class的简介
class可以看作是一个语法糖,目的是让写出来的代码更加简洁明了。
class语法创建实例对象与传统方法的差异:
传统方法通过构造函数实现:
function square(height,width){
this.height = height;
this.width = width;
}
square.prototype.area = function(){
return this.height * this.width;
}
let a_square = new square(50,100);
console.log(a_square,a_square.area());
--------------------------------------------log
square {height: 50, width: 100} 5000
class语法创建实例对象
class square {
constructor(height, width) {
this.height = height;
this.width = width;
}
area(){
return this.height * this.width;
}
}
var a_square = new square(50,100)
console.log(a_square,a_square.area());
--------------------------------------------log
square {height: 50, width: 100} 5000
由两图可以明显看出,class创建实例更偏向于面向对象的写法,辨识度更高,更容易理解。
滴滴: 类上定义的方法,实例会继承。即实例.fun()===类.prototype.fun()。
如下:
a_square.area === square.prototype.area
true
constructor方法
class会默认创建constructor方法并返回实例对象(即this),当然,是在你未定义constructor的时候。
所以你可以在constructor方法内部定义实例需要继承的属性及属性值。
getter和setter 取值函数和存值函数
简单说getter和setter作用:
如果一个class定义的有getter和setter——class创建实例后,想要访问实例的某个属性,会先调用getter方法;想要设置实例的某个属性,会先调用setter方法。
class square {
constructor(height, width) {
this.height = height;
this.width = width;
}
get height(){
console.log('调用getter')
return 10
}
set height(val){
console.log('调用setter', val)
}
}
var a_square = new square()
a_square.height
---调用setter undefined
---调用getter
---10
a_square.height = 1000
---调用setter 1000
---1000
属性和类的表达式模式
let name = "squareNum1"
const dis = class square {
constructor(height, width) {
this.height = height;
this.width = width;
}
[name](){
console.log('squareNum1')
}
}
var disExample = new dis()
disExample.squareNum1()
---squareNum1 //dis变量接收类直接new实例
---undefined
dis.squareNum1
---undefined
dis.squareNum1()
----VM1376:1 Uncaught TypeError: dis.squareNum1 is not a -----function
--- at <anonymous>:1:5
---(anonymous) @ VM1376:1
dis.prototype.squareNum1() //类上的方法需要在原型链上找
---squareNum1
---undefined
二、static静态方法
简述static:创建class的时候,可以通过static创建无法被实例继承的方法。只能使用类调用该方法去执行。
class square {
static getName(){
return 'static静态方法'
}
getAge(){
return '非静态方法'
}
}
var a_square = new square()
a_square.getAge()
---"非静态方法"
square.getName()
---"static静态方法"
实例属性的其他写法
直接在class类的最顶端定义属性及属性值
之前说的是在constructor方法中定义属性及属性值
class square{
name = 'zhuo'
area(){
console.log('调用area')
}
}
var a_square = new square()
a_square.name
"zhuo"