原型与原型链是初级前端必备技能,也是前端面高频面试题之一,在此记录一下。
class原型的本质
- ES6 的 class 可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的 class 写法只是让对象原型的写法更加清晰、更像面向对象编程的语法
- 类的本质是一个函数,类自身指向的就是构造函数
- 原型链代码实例:
//父类
class People {
constructor(name) {
this.name = name;
}
walk() {
console.log(this.name + "go to school");
}
}
//子类
class Student extends People {
constructor(name, score, number) {
super(name);
this.score = score;
this.number = number;
}
sayNice() {
console.log(this.name + "是窝窝乡" + this.number + "妖侠");
}
}
//子类
class Teacher extends People {
constructor(name, major) {
super(name);
this.major = major;
}
explain() {
console.log(this.name + "教" + this.major);
}
}
//声明实例
let manji = new Student("蛮吉", "100", "001");
console.log(manji.name);//蛮吉
manji.sayNice(); //蛮吉是窝窝乡001妖侠
manji.walk(); //蛮吉去挑战村长
//声明实例
let manxiaoman = new Teacher("蛮小满", "霸王冲");
console.log(manxiaoman.name); //蛮小满
manxiaoman.explain();//蛮小满教霸王冲
manxiaoman.walk(); //蛮小满去挑战村长