class的基本语法
在ES6标准中提供class关键字来定义类,在写法上更简洁、语义化更强。
class People{
constructor(name,age){
this.name = name;
this.age = age;
}
Instring(){
console.log('我喜欢羽毛球');
}
}
ES5是利用构造函数实现类:
function People(name,age){
this.name = name;
this.age = age;
}
People.prototype.Instring = function(){
console.log('我喜欢羽毛球');
}
ES6 的class与ES5写法的几个核心注意点:
1、ES5 的构造函数Point,对应 ES6 的Point类的构造方法。
2、类的所有方法都定义在类的prototype属性上面。
3、定义“类”的方法的时候,前面不需要加上function这个关键字,直接把函数定义放进去了就可以了。
4、方法之间不需要逗号分隔,加了会报错。
5、ES6的class使用方法与ES5的构造函数一模一样。
constructor构造方法
constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。
constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象。
类的调用
类必须使用new调用。
class People{
constructor(name,age){
this.name = name;
this.age = age;
}
Instring(){
console.log('我喜欢羽毛球');
}
}
let people = new People('小萱',21);
people.Instring();
如果不使用new则会报错。
class People{
constructor(name,age){
this.name = name;
this.age = age;
}
Instring(){
console.log('我喜欢羽毛球');
}
}
People()//Class constructor People cannot be invoked without 'new'
Instring();//Instring is not defined
ES6支持通过getter、setter在原型上定义属性。
创建getter的时候需要用关键字get;创建setter的时候需要用关键字set。
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
get name(){
return this._name
}
set name(newName){
this._name = newName
}
get age(){
return 20;
}
set age(newValue){
this._age = newValue
}
}
let p = new Person('小萱',21);
console.log(`姓名:${p.name},年龄:${p.age}`);//姓名:小萱,年龄:20
静态属性和方法
类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
class Person{
static num = 20; //静态属性
constructor(name){
this.name = name;
this.age = 20;
}
static fun() { //静态的成员方法
console.log("fun...")
}
}
let p = new Person('小萱',21);
Person.fun();//fun...
console.log(Person.num);//20
ES5实现静态属性和方法
function Person(name){
this.name = name;
this.age = 20;
}
Person.num = 10; //静态属性
Person.fun = function() { //静态方法
console.log("fun...")
}
let p = new Person('小萱',21);
Person.fun();//fun...
console.log(Person.num);//20
ES6标准中类的继承
ES6标准中类的继承:通过extends关键字实现。
在继承中需要调用super()方法继承父类的构造方法。super()在使用过程中需要注意以下两点:
A、在访问this之前一定要调用super()。
B、如果不调用super(),可以让子类构造函数返还一个对象。
class Father {
constructor(name){
this.name = name;
}
fun() {
console.log('我是父类的方法')
}
}
class Son extends Father {
constructor() {
super();
}
hobby() {
console.log('我喜欢篮球')
}
}
let son = new Son();
son.fun();
在ES5标准中可以通过call、apply、bind来实现构造函数的继承,实现方式如下:
function Father(name) {
this.name = name;
this.age = 20;
}
function Son(name) {
Father.call(this,name);
//Father.apply(this,[name]);
//Father.bind(this)(name);
this.height = "178com";
}
上述方式可以实现构造函数的继承,但是如果有方法在Father原型上实现,还需要考虑原型的继承,单纯的原型赋值继承还会涉及传址问题,所以实现起来比较繁琐。