es6 class类

秒速五厘米 2022-06-08 02:13 344阅读 0赞

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;
}

  1. static distance(a, b) \{
  2. const dx = a.x - b.x;
  3. const dy = a.y - b.y;
  4. return Math.sqrt(dx\*dx + dy\*dy);
  5. \}

}

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;
}

  1. speak() \{
  2. console.log(this.name + ' makes a noise.');
  3. \}
  4. \}

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 条评论,344人围观)

还没有评论,来说两句吧...

相关阅读

    相关 ES6中新增class

    我们都知道JavaScript是弱类型的语言,其缺陷就是缺乏严谨性,但是在JavaScript发展的过程中需要慢慢的弥补这些缺陷,于是便在ES6中出现了类的概念。 文

    相关 ES6 class

    ES6中的类 js中生成实例对象的传统方法是通过构造函数。而ES6提供了更接近传统语言的写法,引入了class类这个概念,作为对象的模板,通过class类关键字,可以定义

    相关 ES6 class的继承

    类的继承:`extends`关键字用于[类声明][Link 1]或者[类表达式][Link 2]中,以创建一个类,该类是另一个类的子类。 `extends`关键字用来创建一个

    相关 ES6--Class

    Class概述 概述 在ES6中,class (类)作为对象的模板被引入,可以通过 class 关键字定义类。 class 的本质是 function。 它可以