作业-2

本文探讨了ES6中类的定义与使用,包括构造函数、原型链以及继承的概念。通过示例解释了子类如何调用父类的构造函数,并强调了在子类初始化时必须先调用super的重要性。此外,还展示了静态方法的继承和调用规则。最后,给出了一个Animal类的子类Cat,展示如何扩展类并添加新的方法。
摘要由CSDN通过智能技术生成

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('这是新增的方法')
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值