在ES6中增加了类的概念,可以使用class关键字声明一个类,之后以这个类来实例化对象
类抽象了对象的公共部分,它泛指某一大类(class) 对象特指某一个,通过类实例化一个具体的对象
如 明星、歌手、电影演员、电视演员、都指一类、
歌手实例化对象 =》王力宏 是一个具体的对象
歌手这个类有实例化对象的公共部分:例如 出专辑 粉丝应援外号 特点 具体的一些动作......
constructor() 方法是类的构造函数(默认方法),用于传递参数,返回实例对象通过 new 命令自动调用该方法,如果不手动写 类内部也会自动创建
constructor 里的this 指向实例化的对象
创建新的实例 new 关键字不能省略
new 在执行时会做着四件事
1.内存中创建一个新的对象
2.让this指向这个新的对象
3.执行构造函数代码 给对象数据
4.返回这个对象 (所以不用return)
- 声明一个明星的类
- class Star {
- constructor(uname,num){
- this.uname = uname
- this.number = num
- }
- rap(sang){
- console.log(this.uname+'唱了'+sang)
- }
- }
-
-
- 实例化两个对象
- let wlh = new Star('王力宏','38')
- let lll = new Star('李靓蕾','32')
-
-
- 打印输出
- console.log(wlh,lll);
- console.log(wlh.uname,lll.number)
- wlh.rap('我们的歌')
- lll.rap('情人总分分合合可是我们')
constructor 里的this 指向实例化的对象
方法里的this指向实例调用者 可以使用 bind 方法更改this 指向
使用extends 关键字 继承父类
在构造函数内使用super (必须放在第一行)来选择性接收参数
如果实例化子类输出一个方法,先看子类有没有这个方法,如果有就先执行子类的如果没有就去父类查找
class 子类 extends 父类{
constructor(x,y){
super(x,y)
this.x = x
this.y = y
}
}
- class Father{
- constructor(x,y) {
- this.x = x
- this.y = y
- }
- sum(){
- console.log(this.x + this.y);
- }
- cheng(){
- console.log(this.x * this.y)
- }
- money(){
- console.log('1100万')
- }
- say(){
- return '我是father'
- }
- }
- class Son extends Father{
- constructor(x,y) {
- super(x,y);
- this.x = x
- this.y = y
- }
- yu(){
- console.log(this.x % this.y)
- }
-
-
- }
-
- let son = new Son(1,2)
- let son2 = new Son(92,7)
- console.log(son)
- son.sum()
- son2.cheng()
- son.money()
- console.log(son.say());
- son2.yu()
加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。 如果静态方法包含this关键字,这个this指的是类,而不是实例。注意与类中普通方法:类的方法内部如果含有this,它默认指向类的实例。 静态方法不能被实例调用,只能通过类来调用。