es6 class类
class类
class Person {
constructor(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.friends = [‘Shelby’,’Court’];
}
sayName () {
console.log(this.name);
}
}
let person = new Person(‘张三’,26,’司机’);
person.sayName();
2.静态方法:
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.sqrt(dx\*dx + dy\*dy);
\}
}
const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
console.log(Point.distance(p1, p2));
3.ES6明确规定,Class内部只有静态方法,没有静态属性,但可以用另外方式解决
class Foo {
}
Foo.prop = 1;
Foo.prop // 1
//—-单例模式
class Cache {
static getInstance() {
if (!Cache.instance) {
Cache.instance = new Cache();
}
return Cache.instance;
}
}
var cache = Cache.getInstance();
4.继承:
class Animal {
constructor(name) {
this.name = name;
}
speak() \{
console.log(this.name + ' makes a noise.');
\}
\}
class Dog extends Animal {
speak() {
console.log(this.name + ‘ barks.’);
}
}
let dog = new Dog(‘旺财’);
dog.speak();
//—————————-vue中loginbean的单例模式—————————————
class LoginBean {
static getInstance() {
if (!LoginBean.instance) {
LoginBean.instance = new LoginBean();
}
return LoginBean.instance;
}
constructor() {
this.id = 0;
this.nicheng = null;
}
}
var loginbean = LoginBean.getInstance();
export default loginbean;
还没有评论,来说两句吧...