class Person{ constructor(name,age,sex){ this.name = name; this.age = age; this.sex = sex; } getSex(){ return this.sex; } isMan(){ return this.sex === 1; } isWomen(){ return this.sex === 0; } } class Man extends Person{ constructor(options) { super(options.name,options.age,1); this.strength = options.strength || 10; } getInfo(){ return { name:this.name, age:this.age } } isStrong(){ return this.strength > 20; } } class Women extends Person{ constructor(options) { super(options.name,options.age,0); } getInfo(){ return { name:this.name, age:this.age } } } //在这里new一个实例 var man = new Man({ name:'张三', age:18, strength:30 }); console.log(man.getInfo(),man.isMan(),man.isStrong())// name:“张三”,age:“18” ,true,true var w = new Women({ name:'张一', age:18, strength:30 }); console.log(w.getInfo(),w.isMan()) // name:“张一”,age:“18” ,false
以上案例很简单的用了继承属性及super关键字,如果明白了,那么下面的这个案例既可以测试下,来看看打印结果是什么吧?
class Father { test(){ return 0; } static test1(){ return 1; } } class Child extends Father { constructor(){ super(); } } //调用父类方法, super 作为对象,在普通方法中,指向父类的原型对象,在静态方法中,指向父类 class Child2 extends Father { constructor(){ super(); // 调用父类普通方法 console.log(super.test()); } static test3(){ // 调用父类静态方法 return super.test1+2; } } Child2.test3();
console.log(super.test()); 这个打印结果是 0
Child2.test3(); 这个的打印结果是 3
好了,很简单,应该都知道吧。最近想再回顾下es6的语法,就想写此博客记录下