JavaScript的写类方式(6)

时间到了2015年6月18日,ES6正式发布了,到了ES6,前面的各种模拟类写法都可以丢掉了,它带来了关键字 class,constructor,set,get,extends,super。

 

ES6的写类方式

// 定义类 Person
class Person {

  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  setName(name) {
    this.name = name;
  }

  getName() {
    return this.name;
  }

  toString() {
    return 'name: ' + this.name + ', age: ' + this.age;
  }

}

// 创建实例对象
var p = new Person('Backus', 35);
p instanceof Person; // true

以上定义了一个类,constructor 是构造器,这点和 Java 不同,Java的构造器名和类名相同。constructor 这种简写语法来定义构造函数,因此不需要添加 function 关键字。

 

需要注意:

  • 字段属于该类对象,不会出现在原型(prototype)上,如本例的name,age
  • 字段只能在constructor中定义

 

也可以使用表达式方式创建类

let Person = class {

    constructor(name, age) {
      this.name = name;
      this.age = age;
    }
  
    setName(name) {
      this.name = name;
    }
  
    getName() {
      return this.name;
    }
  
    toString() {
      return 'name: ' + this.name + ', age: ' + this.age;
    }  
}

 

ES6 还带来了属性访问器,set,get 后空格跟上对应的标识符即可

class Person {
    constructor(name, age) {
      this._name = name;
      this._age = age;
    }
  
    set name(v) {
      this.name = v;
    }
    get name() {
      return `Name is ${this._name}`;
    }
    set age(v) {
        this.age = v;
    }
    get age() {
        return `Age is ${this._age}`;
    }

    get desc() {
        return this.name + ', ' + this.age;
    }
}
var p = new Person('Tim', 30);
console.log(p.name, p.age);
console.log(p.desc);

这里需要注意,使用访问器后 constructor 中的字段建议添加一个下划线(_)以区分访问器属性,否则会报错。访问器属性有强大的功能,你可以在其中添加额外的代码逻辑,此时赋值(使用=)或取值(使用.)将触发访问器函数代码。

 

再看看继承

class Man extends Person {
  constructor(name, age, school) {
    super(name, age); // 调用父类构造器
    this.school = school;
  }

  setSchool(school) {
    this.school = school;
  }

  getSchool() {
    return this.school;
  }

  toString() {
    return super.toString() + ', school:' + this.school; // 调用父类的toString()
  }
}

var man = new Man('张三', '30', '光明中学');
man instanceof Man; // true
man instanceof Person; // true
console.log(man);

以上代码中,constructor 和 toString 方法中,都出现了 super 关键字,它指代父类的实例(即父类的 this 对象)。 之前 ES5 有个 Object.getPrototypeOf 来获取父类的原型对象

 

 

可以继续阅读:

JavaScript继承方式(1)

posted on 2016-04-08 08:04  snandy  阅读(2510)  评论(3编辑  收藏  举报