es6 class类
2022-03-01 15:58 孤独大兔子 阅读(118) 评论(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关键字可以定义一个类,这里新增的类写法,只是 一个语法糖,是为了对象原型的写法更加清晰、更像面向对象编程的语法。
//定义类
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
var p = new Point(1, 2);
class Point {
// ...
}
typeof Point // "function"
Point === Point.prototype.constructor // true
有几点需要说的:
1、写法不同而已,实现都可以实现。
2、用class定义的类,需要注意,中间没有逗号、不用写function。
class Point {
constructor(){
// ...
}
toString(){
// ...
}
toValue(){
// ...
}
}
// 等同于
Point.prototype = {
toString(){},
toValue(){}
};
3、类内部写的方法定义在类的prototype属性上面,constructor定义自己的属性

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

5、类的内部所有定义的方法,不可枚举,ES5中prototype方法添加属性可以被枚举。
class Point {
constructor(x, y) {
// ...
}
toString() {
// ...
}
}
Object.keys(Point.prototype)
// []
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]
6、不存在变量提升
//-----函数声明-------
//定义前可以先使用,因为函数声明提升的缘故,调用合法。
func();
function func(){}
//-----定义类---------------
new Cat(); //报错,Cat is not defined
class Cat{}
7、可以用表达式方式创建
const MyClass = class Me {
getClassName() {
return Me.name;
}
};
8、class的继承,继承后再在原型上添加属性,不可以改变原始类的属性。
//定义类父类
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关键字就可以了。
// 老写法
class Foo {
}
Foo.prop = 1;
// 新写法
class Foo {
static prop = 1;
}
10、没了
浙公网安备 33010602011771号