1、class的基本语法(创建私有的属性)
class Fn {
constructor(x) {
this.x = x;
//设置私有的属性
// this.y = 200;
}
y = 200; //ES7: this.y = 200 设置的是私有的属性;等同于上面constructor里面设置
}
2、设置原型上面的方法
class Fn {
constructor(x) {
this.x = x;
//设置私有的属性
// this.y = 200;
}
y = 200; //ES7: this.y = 200 设置的是私有的属性;等同于上面constructor里面设置
//---- Fn.prototype
getX() {} //这个方法没有prototype
}
3、设置静态的私有的属性和方法
class Fn {
constructor(x) {
this.x = x;
//设置私有的属性
// this.y = 200;
}
y = 200; //ES7: this.y = 200 设置的是私有的属性;等同于上面constructor里面设置
//---- Fn.prototype
getX() {} //这个方法没有prototype
//---- 设置静态私有属性方法
static m = 400;
// static getM = function () {} //有prototype
static getM() {} //没有prototype
}
4、Fn.prototype.z = 300; //公有的属性只能外侧单独加
5、class创建的类只能通过new 执行,不能直接调用;会报错
// Fn(); //=>Uncaught TypeError: Class constructor Fn cannot be invoked without 'new' 基于class创建的类只能被new执行
6、小提示
(1)这种创建的函数带prototype
(2)这种创建的函数不带prototype
7、设置原型上的方法
(1)getX这样创建只是相当于加了一个私有属性
(2)必须这种方式进行创建