一. Class基础用法:
在ES6之前我们一般这样写
function Cat(name) {
this.name = name;
}
Cat.prototype.sayName = function() {
console.log("name: " + this.name);
}
var cat = new Cat('ZZ');
cat.sayName();
ES6引入Class后这个函数就可以这样写
class Cat {
constructor(name) {
this.name = name;
}
sayName() {
console.log("name: " + this.name);
}
}
var cat = new Cat('ZZ');
cat.sayName();
这样写有点感觉类似java中类的写法。
当你用 new 生成实例时 constructor方法就会自动调用,即使你没有定义方法 也会默认添加的
constructor方法被调用时就会接受传递的参数。
这里有两点需要注意:
1.
class Cat {
constructor(name) {
this.name = name;
}
sayName() {
console.log("name: " + this.name);
}
}
Cat();
这样写是会报错的 因为当你用Class时 必须用new声明实例
2.
var cat = new Cat("ZZ");
class Cat {
constructor(name) {
this.name = name;
}
sayName() {
console.log("name: " + this.name);
}
}
这样写也是会报错的( Cat is not defined) 因为 Class不存在变量提升了。
二. 继承:
继承的代码是这样的:
class animal {
constructor(name) {
this.name = name;
}
run() {
console.log('name: ' + this.name + ' run run');
}
}
class Cat extends animal {
constructor(name, age) {
super(name);
this.age = age;
}
sayName() {
console.log("name: " + this.name + ' age: ' + this.age);
}
}
var cat = new Cat("xiaoMing", 17);
cat.run();
cat.sayName();
运行结果是:
name: xiaoMing run run
name: xiaoMing age: 17
Class的继承通过extends 实现
然后在子类Cat中的 constructor 方法内 通过super 向父类传递参数
这里有两点需要注意
1 constructor 方法内必须写super 否则会报错
2.super之前使用this关键字是会报错的
像这样
this.age = age;
super(name);
三.取值函数(getter)和存值函数(setter)
代码:
class Cat{
constructor() {
}
get age() {
return this.num;
}
set age(num) {
this.num = num;
}
}
var cat = new Cat();
cat.age = 17;
console.log('cat age: ' + cat.age);//17
四 Class静态方法(static)
当我将某个方法加上 static关键字时 这个方法就不会被实例继承,只能通过类来调用
这句话的意思用代码表示就是:
class animal {
constructor(name) {
this.name = name;
}
run() {
console.log('name: ' + this.name + ' run run');
}
static walk() {
console.log('walk walk');
}
}
class Cat extends animal {
constructor(name, age) {
super(name, age);
}
}
var cat = new Cat('xiaoMing', 17);
cat.run();
cat.walk();
animal.walk();
Cat.walk();
这段代码在运行时就会报错 (cat.walk is not a function)
当把
cat.walk();
注释掉就不会报错了.
仔细观看代码你会发现 父类和子类都可以调用这个被static修饰的 方法.