class和继承
class基本使用
class Student{
constructor(name, number) {
this.name = name
this.number = number
}
sayHi () {
console.log(`姓名:${this.name} 学号:${this.number}`);
}
}
const zs = new Student('zs', 100)
console.log(zs.name);
console.log(zs.number);
zs.sayHi()
继承基本使用
// 父类
class People{
constructor(name) {
this.name = name
}
eat () {
console.log(`${this.name} eat something`);
}
}
// 子类
class Student extends People{
constructor(name, number) {
super(name)
this.number = number
}
sayHi () {
console.log(`姓名:${this.name} 学号:${this.number}`);
}
}
class Teacher extends People{
constructor(name, major) {
super(name)
this.major = major
}
teach () {
console.log(`${this.name} 教授 ${this.major}`);
}
}
const zs = new Student('zs', 100)
console.log(zs.name);
console.log(zs.number);
zs.sayHi()
zs.eat()
const wang = new Teacher('王', '语文')
console.log(wang.name);
console.log(wang.major);
wang.teach()
wang.eat()
JS原型
instanceof类型判断
- A instanceof B === true
- A是B构造出来的一个实例
- 如果C是B的父类,A instanceof C===true也成立
- Object是所有类的父类
-
隐式原型和显式原型
隐式原型:proto
显式原型:prototype
- 每个class都有显式原型prototype
每个实例都有隐式原型proto
实例的__proto指向对应class的prototype
获取属性或执行方法时,先在自身属性和方法寻找,如果找不到则去proto中查找
原型链
People.prototype === Student.prototype.proto
- class是ES6语法规范,由ECMA委员会发布。
ECMA只规定语法规则,即我们代码的书写规范,不规定如何实现。
以上实现方式都是V8引擎的实现方式,也是主流的。
相关面试题
- 如何准确判断一个变量是不是数组?
- a instanceof Array
- 手写一个建议的jQuery,考虑插件和扩展性
- class的原型本质如何理解?
- 原型和原型链
- 属性和方法的执行规则