注释很详细,直接上代码
新增内容:
1. 类的基本用法
2. 类的继承用法
3. 类的this指向问题
项目结构:
仅一个文件
源码:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button>点击</button>
</body>
<script>
//基础用法
//-------------------------------------------------------🌹🌹🌹
//对象Person -类名一般首字母大写
class Person {
constructor(name, age) {
//构造函数
this.name = name;
this.age = age;
}
say() {
//say方法(无参)
alert(this.name + "今年" + this.age + "岁了");
}
worship(name) {
//worship方法(有参)
alert(this.name + "膜拜膜拜" + name);
}
}
/*
let p = new Person("张三", 20); //实例化新对象
p.say(); //调用say方法
p.worship("眨眼睛一号");//调用worship方法
*/
//继承用法
//-------------------------------------------------------🌹🌹🌹
class Student extends Person {
//继承Person类
constructor(name, age, school) {
//构造函数
super(name, age); //调用父类的构造函数
this.school = school;
}
say() {
//重载say方法,如无,则默认调用父类的say方法
alert(this.name + "今年" + this.age + "岁了,学校是" + this.school);
}
worship(name) {
//super调用父类的worship方法
super.worship(name);
}
yyds(name) {
//子类扩展自身的方法
alert(name + "yyds!");
}
}
/*
let s = new Student("李四", 18, "B站大学");
s.say();
s.worship("眨眼睛二号");
s.yyds("眨眼睛");
*/
//类中的this指向
//-------------------------------------------------------🌹🌹🌹
let that;
class Star {
constructor(uname, age) {
// constructor 里面的this指向的是创建的实例对象,储存起来可以使一些嵌套了的方法可以使用该对象的this
that = this;
this.uname = uname;
this.age = age;
this.btn = document.querySelector("button");
this.btn.onclick = this.sing;
}
sing() {
// 这个sing方法里面的this 指向的是 btn 这个按钮,因为这个按钮调用了这个函数
console.log(this);
console.log(that); // that里面存储的是constructor里面的this
}
}
var ldh = new Star("刘德华");
</script>
</html>
效果演示:
为了更清晰进行了注释,小友按着分类解开注释一个个看吧