代码改变世界

es6 class类

  孤独大兔子  阅读(112)  评论(0编辑  收藏  举报

JavaScript语言的传统方法是通过构造函数,定义并生成新对象。

复制代码
function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function () {
  return '(' + this.x + ', ' + this.y + ')';
};

var p = new Point(1, 2);
复制代码

ES6引入了CLASS概念,通过class关键字可以定义一个类,这里新增的类写法,只是 一个语法糖,是为了对象原型的写法更加清晰、更像面向对象编程的语法。

1
2
3
4
5
6
7
8
9
10
11
//定义类
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
 
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}var p = new Point(1, 2);
1
2
3
4
5
6
class Point {
  // ...
}
 
typeof Point // "function"
Point === Point.prototype.constructor // true

 有几点需要说的:

1、写法不同而已,实现都可以实现。

2、用class定义的类,需要注意,中间没有逗号、不用写function。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Point {
  constructor(){
    // ...
  }
 
  toString(){
    // ...
  }
 
  toValue(){
    // ...
  }
}
 
// 等同于
 
Point.prototype = {
  toString(){},
  toValue(){}
};

3、类内部写的方法定义在类的prototype属性上面,constructor定义自己的属性

 

 

 4、类虽然同方法很像,但不能直接调用,需要通过new来调用

 

 

 5、类的内部所有定义的方法,不可枚举,ES5中prototype方法添加属性可以被枚举。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Point {
  constructor(x, y) {
    // ...
  }
 
  toString() {
    // ...
  }
}
 
Object.keys(Point.prototype)
// []
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]

6、不存在变量提升

1
2
3
4
5
6
7
8
//-----函数声明-------
//定义前可以先使用,因为函数声明提升的缘故,调用合法。
func();
function func(){}
 
//-----定义类---------------
new Cat();  //报错,Cat is not defined
class Cat{}

7、可以用表达式方式创建

1
2
3
4
5
const MyClass = class Me {
  getClassName() {
    return Me.name;
  }
};

8、class的继承,继承后再在原型上添加属性,不可以改变原始类的属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//定义类父类
class Parent {
    constructor(name,age){
        this.name = name;
        this.age = age;
    }
 
    speakSometing(){
        console.log("I can speek chinese");
    }
}
//定义子类,继承父类
class Child extends Parent {
    coding(){
        console.log("coding javascript");
    }
}
 
var c = new Child();
 
//可以调用父类的方法
c.speakSometing(); // I can speek chinese

9、新写法,类的静态属性只要在上面的实例属性写法前面,加上static关键字就可以了。

1
2
3
4
5
6
7
8
9
// 老写法
class Foo {
}
Foo.prop = 1;
 
// 新写法
class Foo {
  static prop = 1;
}

10、没了

相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示