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; 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值