ES6的介绍
ES6是即将到来的新版本JavaScript语言的标准,他给我们带来了更”甜”的语法糖(一种语法,使得语言更容易理解和更具有可读性,也让我们编写代码更加简单快捷),如箭头函数(=>)、class等等。
class ES6引入了类的概念,它可以看作是一个语法糖,因为class实现的功能ES5都实现了。
创建一个class函数
-
首先来看一下es5创建一个class
function Person(name,age,sex){ this.name = name; this.age = age; this.sex = sex; } Person.prototype.sayName = function(){ alert(this.name) } Person.prototype.setName = function(newName){ this.name = newName; } var p1 = new Person('lili',12,'女')
并且通过new关键字调用的函数叫构造函数。
-
其次用ES6的方式来创建一个class函数
- 什么是class函数?
class是关键字,后面紧跟类名,类名首字母大写,采取的是驼峰命名法则。
类名之后是{},在{}中,不能直接写语句,只能写方法,方法不需要使用关键字,
方法和方法之间没有逗号,不是键值对。
class Person {
constructor(name,age,sex){ //是类的默认方法,在调用new时,会自动执行
this.name = name;
this.age = age;
this.sex = sex;
}
sayName(){
alert(this.name);
}
setName(newName){
this.name = newName;
}
static add(){ //静态方法需要添加static关键字
console.log('add');
}
static address='河北省' //静态属性需要添加static关键字
}
let p2 = new Person('小明',24,'男');
typeof Person // "function"
Person === Person.prototype.constructor // true
- 注:
实例的属性必须要在constructor里面定义
函数的继承
- es5的继承方式
function Student(){
Person.apply(this,arguments);
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
- es6的继承方式
class student extends Person{ //clss后是子类函数 extends 后为父类函数
constructor(name,age,sex){
super(name,age,sex);
}
setId(id){ //新增的方法 对象中简写方法,省略function
this.id = id;
}
}
注:静态方法和静态属性不能被实例调用,必须使用类调用
此文章只是使用初次接触class函数的新人