JS基础 - Class 原型 原型链
1. class的基本使用
class Student { constructor(name, number){ this.name = name; this.number = number; } sayHi(){ console.log( `姓名 ${this.name} , 学号 ${this.number}` ) } }
要点:
- 构造函数名为constructor, 前面没有function关键字
- 属性
- 实例属性:直接从构造函数传入,然后复制给this
- 公共属性:通过prototype添加 - Student.prototype.a = 2;
- name属性:返回跟在class后面的类名
- 方法
- 原型方法:在constructor外定义,没有function关键字
- 实例方法:在constructor内赋给this - this.sum = (a, b) => {return a+b;}
- 静态方法:在constructor外定义,加上static关键字
- 类定义不会被提升,必须在访问前先进行定义
2. 原型/构造函数/实例间的关系
每个构造函数含有显示属性prototype,指向原型
每个实例有隐式属性__proto__,指向原型
原型有隐式属性__proto__,指向其直接父类的原型 => 原型链
3.
hasOwnProperty:检查是否是实例属性,不包括原型及原型链上继承来的
for(let key in obj): 遍历所有属性,包括原型及原型链上继承来的
instanceof:查找整个原型链
访问属性/方法:实例 -> 原型 -> 原型链