1. es5 类写法
function People(name) { this.name = name; } People.prototype.getName = function () { return this.name; }; var people = new People("strick"); console.log(people.getName());
static a = 20; // 等同于 Person.a = 20
继承 extends
class Student extends Person {}
继承的构造函数中,我们必须如上面的例子那么调用一次super方法,它表示构造函数的继承,与ES5中利用call/apply继承构造函数是一样的功能。
2. es6 类写法
class People { constructor(name) { this.name = name; } getName() { return this.name; } }
3. es6 类相关概念
3.1 表达式
var People = class Man { getSelf() { console.log(typeof Man); //"function" console.log(Man.name); //"Man" console.log(new Man().getAge()); //28 return 'hello'; } getAge() { return 28; } }; var people = new People(); console.log(people.getSelf()); console.log(People.name); //"Man" console.log(Man.name); //Man未定义的错误
3.2 立即执行
var people = new class { constructor(name) { this.name = name; }; getName() { return this.name; }; }("strick"); console.log(people.getName()); //"strick"
3.3 自有属性
class People { constructor() { this.name = "strick"; } }
3.4 访问器属性
class People { get prop() { return `getter:${this.name}`; } set prop(value) { this.name = value; } } var people = new People(); people.prop = "strick"; console.log(people.prop); // getter:strick
3.5 计算成员名
var method = "getAge"; class People { ["get" + "Name"]() { return "strick"; } [method]() { return 28; } } var people = new People(); console.log(people.getName()); //"strick" console.log(people.getAge()); //28
3.6 生成器
class People { * getName() { yield "strick"; } } var people = new People(), iterator = people.getName(); console.log(iterator.next()); //{value: "strick", done: false}
3.7 静态方法
class People { static getName() { return "strick"; } getName2() { return "strick"; } } var people=new People(); console.log(people.getName2());