一,类的属性在 constructor 定义和赋值
class Person{ constructor(name,age){ this.name = name; this.age=age; } } let p = new Person('Jack',21); console.log('name : ' + p.name + ' , age : ' + p.age);
二,类的 constructor 默认返回类的实例,也可以返回其他类的实例
class Work{ constructor(company, location){ this.company = company this.location = location } toJson(){ return {'company' : this.company,'location' : this.location} } } class Person{ constructor(name,age){ this.name = name this.age=age return new Work('Tencent','Shenzhen') } } let p = new Person('Jack',21); console.log(p.toJson());
三,子类继承父类,必须在 constructor 中先执行 super(),才能绑定父类的 this 到子类
class Person { constructor(name,age){ this.name = name this.age=age } info(){ return {'name' : this.name,'age' : this.age} } } class Student extends Person { constructor(name, age, school, grade){ super() this.school = school this.grade = grade this.name = name this.age = age } } let s = new Student('Jack',21,'SCNU',5); console.log(s.info());
四,类的实质是函数,自身就是构造函数,可以通过 prototype 和 Object.assign 来修改类的属性和方法
class Person { constructor(name,age){ this.name = name this.age=age } } Person.prototype.toJson=function(){ return {'name':this.name,'age':this.age} } Object.assign(Person.prototype,{ getName:function(){ return this.name; } }) let o = new Person('Jack',21); console.log(o.toJson()); console.log(o.getName());
Leave a Reply