1.编写程序使用ES6定义 Person类
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
say(){
console.log(`姓名是:${this.name},年龄是${this.age}`)
}
}
var peple = new Person('王大陆',22);
peple.say();
2.下面程序执行结果为:
var p=new Person();
console.log(p.__proto__===Person.prototype)
假设Person是一个类,返回结果为true
假设Person是一个构造函数,返回结果为true
下面程序正确吗?错在哪里?如何改正?
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
class ColorPoint extends Point {
constructor(x, y, color) {
this.color = color; // ReferenceError
super(x, y);
}
}
var cp=new ColorPoint(10,20,'red');
在子类继承父类以后,如果不优先书写super方法,无法使用this方法,这是因为
子类的构建是基于父类加工的,在调用super方法以后,才能对父类进行实例,可
以将子类书写为一下格式
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y);
this.color = color; // ReferenceError
}
}
4.下面程序执行结果为?
class Parent {
static myMethod(msg) {
console.log('static', msg);
}
myMethod(msg) {
console.log('instance', msg);
}
}
class Child extends Parent {
static myMethod(msg) {
super.myMethod(msg);
}
myMethod(msg) {
super.myMethod(msg);
}
}
Child.myMethod(1);
var child = new Child();
child.myMethod(2);
输出结果
Child.myMethod(1);的输出结果为static,1
因为Child.myMethod()是静态方法,静态方法只能类调用,且静态方法只能继承,不能复制
child.myMethod(2); 的输出结果为instance,2
由于私有方法只有类可以调用,且实例化对象可以通过super复制父类的属性
5.请利用class重新定义Cat,并让它从已有的Animal继承,然后新增一个方法say()
class Animal {
constructor(name) {
this.name = name;
}
}
class Cat extends Animal {
constructor(name) {
super(name);
}
say(){
console.log('这是新增的方法')
}
}