程序中的类:
- 注意:
1.es6中class没有哦提升功能,在es5中,函数模拟可以,默认函数提升
2.this
矫正this:
1.fn.call(this指向谁,args1,args2…)
2.fn.apply(this指向,[args1,args2…])
3.fn.bind()
class中取值函数(getter),存执函数(setter)
静态方法:类身上的方法,如:
<script > class Person {
constructor() {
} showName() {
return '这是showName方法'; } // 定义静态方法 static aaa() {
return '这是静态方法'; } } let p1 = new Person(); console.log(p1.showName()); // 调用静态方法 console.log(Person.aaa()); </script>
</script>
父类
子类
继承:
之前使用继承(很累):
<script > // 父类 function Person(name) {
this.name = name; } Person.prototype.showName = function () {
return `名字是:${
this.name}`; }; // 子类 function Student(name, skill) {
Person.call(this, name); // 继承属性 this.skill = skill; } Student.prototype = new Person(); // 继承方法 // 调用 let stu1 = new Student("kirin", "逃学"); console.log(stu1.showName()); </script>
现在:
<script > class Person {
constructor(name) {
this.name = name; } showName() {
console.log("父类的showName"); return `名字为: ${
this.name}`; } } class Student extends Person {
// 子类继承父类必须在其中写 super() // constructor:构造函数 /*constructor(args) { super(args); }*/ constructor(name, skill) {
super(name); this.skill = skill; } // 如果子类中有覆盖了父类的方法,则子类方法中必须写super() showName() {
super.showName(); // 父类的方法执行,后面子类的代码还会继续执行 console.log("子类里的showName"); } showSkill() {
return `技能为${
this.skill}`; } } let stu1 = new Student("kirin", "逃学"); // console.log(stu1.showName()); // console.log(stu1.showSkill()); stu1.showName(); </script>