方君の小窝 方君の小窝
首页
  • 原生js总结
  • 样式相关
  • vue
  • 其他必备知识
  • php
其他
GitHub

方君

迷糊小前端
首页
  • 原生js总结
  • 样式相关
  • vue
  • 其他必备知识
  • php
其他
GitHub
  • 原生js总结

    • js基础
    • ajax
    • 跨域,js同步异步
    • promise(待扩展,微队列及all,race案例)
    • 原型、原型链、继承
    • 闭包
    • 设计模式-单例、观察者
    • jquery
    • json格式
    • class
      • 1. class 类
      • 2. extends类的继承
    • 模块化
    • cookie
  • 样式相关

  • vue

  • 其他必备知识

  • 前端
  • 原生js总结
方君
2020-08-24

class

# es6 class类 extend类的继承

# 1. class 类

function Point(x,y){ //构造函数首字母大写 
    this.x=x;
    this.y=y;
}
Point.prototype.toString=function(){
    console.log("x"+this.x+",y="+this.y);
}
var p=new Point(1,2);       //构造函数的使用 new
1
2
3
4
5
6
7
8

因为传统语言,c,java等有class这个概念,所以ES6中新增了一种新的定义构造函数的写法class

es6类class本质是对es5中构造函数的一层包装 !!!

class Point{
                         //所有函数都绑定在prototype里
    constructor(x,y){    //constructor方法相当于绑定在构造函数的constructor中
        this.x=x;
        this.y=y;
    }                    //不需要用,分隔
    
    toString(){          //不需要加function关键字
       console.log("x"+this.x+",y="+this.y);
    }
    
    
}
var p=new Point(1,2);     //使用与普通构造函数一致

console.log(typeof Point);//function
console.log(Point===Point.prototype.constructor)//true

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

class特点:

  1. 定义时内部函数全部绑定在prototype上
  2. 函数之间无需用,(逗号分隔)
  3. 函数不需要添加关键字function
  4. 使用必须要用new关键字,否则报错
  5. 不存在变量提升,只能在类定义之后创建实例

# 2. extends类的继承

class Point{
    
}
class ColorPoint extends Point{
    
}
1
2
3
4
5
6

使用extends继承类,可以继承全部的属性和方法!

子类中的constructor必须使用super调用父类的constructor,否则报错!

因为子类的对象必须先使用父类构造函数,然后再添加新的属性和方法!

class ColorPoint extends Point {
  constructor(x, y, color) {
    super(x, y); // 调用父类的constructor(x, y)
    this.color = color;
  }

  toString() {
    return this.color + ' ' + super.toString(); // 调用父类的toString()
  }
}

//新增方法,获取父类     仅在使用class时有效!
Object.getPrototypeOf(ColorPoint)  //Point
1
2
3
4
5
6
7
8
9
10
11
12
13
编辑
#基础
json格式
模块化

← json格式 模块化 →

最近更新
01
vue自定义指令&生命周期
08-24
02
ajax
08-24
03
promise
08-24
更多文章>
Theme by Vdoing | Copyright © 2019-2020
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式