ES6:class的引入
概要
- ES6的class语法仅仅只是一个语法糖,在ES5中同样可以实现,新的class语法只是为了让对象原型的写法更加清晰,更像面向对象编程语法。
class Point{
constructor(x,y){
this.x = x;
this.y = y;
}
toString(){
console.log( '(' + this.x + ',' + this.y + ')');
}
}
// 调用
let a = new Point(1,2);
a.toString();
//输出
(1,2)
-
在类的实例上调用方法,实际上就是在调用原型的方法;
-
类内部定义的方法都是不可枚举的;
-
类必须使用new来调用,否则会报错;
class表达式
- 与函数一样,class也可以用表达式的形式定义;
const myclass = class me{
getClassName(){
return me.name;
}
}
let a = new myclass();
a.getClassName();
// 输出
"me"
- 从上面的例子可以看出,me只在内部class中有用,外部调用时还是利用变量名称myclass;
不存在变量提升
- 类不存在变量提升,因此在类定义之前不能够调用它;
私有方法和属性
- 在ES6的class中没有提供private关键字,但目前有一种提案,采用#作为私有标志
class Me{
#name
#age = 20
// #getmoney() {return 100}
constructor(name){
this.#name = name;
}
getit(){
console.log('age:' + this.#age);
}
}
let a = new Me('yivi');
a.getit();
//输出
age:20