前言 : ES6引入了Class类的概念,作为对象的模板。这样js对于class类的概念,也更加规范化。
一、创建一个类
class Person{ constructor(name,age){ this.name = name; this.age = age; } showName(){ console.log('name: '+this.name); } } var obj1 = new Person('nikc','男'); obj1.showName();
二、类的继承
class Person{ constructor(name,age){ this.name = name; this.age = age; } showName(){ console.log('name: '+this.name); } } class Person2 extends Person{ constructor(name,age,sex){ super(name,age); //继承 this.sex = sex; } showName(){ //修改方法 console.log("my name is " + this.name); } showSex(){ //新增方法 console.log(this.sex); } } var nick = new Person('nikc',18); nick.showName(); var freddy = new Person2('freddy',20,'男'); freddy.showName(); freddy.showSex();
三、对比
运行代码,可以看到,即便我们修改了showName的方法,也不会影响Person的实例nick的showName方法。