class 声明建立一个基于原型继承的具备给定名称的新类。 你也能够使用类表达式定义类。可是不一样于类表达式,类声明不容许再次声明已经存在的类,不然将会抛出一个类型错误。javascript
申明一个类,Polygon, 而后 Square 来继承 Polygon,只能在构造函数中使用 super()。而且必须在使用 this 关键字前调用。java
使用
extends
建立子类/super
关键字用于调用对象的父对象上的函数。es6
class Cat {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Lion extends Cat {
speak() {
super.speak();
console.log(this.name + ' roars.');
}
}
复制代码
static 静态方法数组
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static distance(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.hypot(dx, dy);
}
}
const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
console.log(Point.distance(p1, p2));
复制代码
get
语法将对象属性绑定到查询该属性时将被调用的函数。var obj = {
log: ['a', 'b', 'c'],
get latest() {
if (this.log.length == 0) {
return undefined;
}
return this.log[this.log.length - 1];
}
}
console.log(obj.latest);
// expected output: "c"
console.log(obj)
// {
// latest: "c"
// log: ["a", "b", "c"]
// }
复制代码
从👆能够看到 latest
在初始化的时候已经被运行了,latest
做为 obj
的一个属性来计算后展现,找到了 log
数组的最后一个值async
使用状况(在每次登录的时候自动的去检测是否登录)函数
class login {
//token存储的键值
static TOKEN_KEY = 'geqwrgfboiadsad';
// 在每次使用这个 class security 的时候 会调用 hasLogin() 来判断是否登陆
get hasLogin() {
return this.currentUser !== null;
}
async signup(params) {
return await http.post(API.signup(), params, {
noToken: true
});
//!!!step1注册只返回邀请码,添加登陆后需再localStorage存储用户信息
}
}
复制代码
get 的使用状况,get 能够在类初始化的使用直接运行,而后做为类的一个属性来使用post
var language = {
set current(name) {
this.log.push(name);
},
log: []
}
language.current = 'EN';
language.current = 'FA';
console.log(language.log);
// expected output: Array ["EN", "FA"]
复制代码
delete obj.lastest
// 这样能够删除 getter
复制代码
var o = { a:0 }
Object.defineProperty(o, "b", { get: function () { return this.a + 1; } });
console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
// get
// ------------
// set
var o = { a:0 };
Object.defineProperty(o, "b", { set: function (x) { this.a = x / 2; } });
o.b = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log(o.a) // 5
复制代码