javascript classes


ECMAScript5 之前使用构造函数实现继承。
之后就用class,看看class-style

class Person {
  constructor(first, last, age, gender, interests) {
    this.name = {
      first,
      last
    };
    this.age = age;
    this.gender = gender;
    this.interests = interests;
  }

  greeting() {
    console.log(`Hi! I'm ${this.name.first}`);
  };

  farewell() {
    console.log(`${this.name.first} has left the building. Bye for now!`);
  };
}


Note: Under the hood, your classes are being converted into Prototypal Inheritance models — this is just syntactic sugar. But I'm sure you'll agree that it's easier to write.  你的类被转换成原型实例化模型, syntactic sugar 语法糖


class Teacher extends Person {
  constructor(subject, grade) {
    this.subject = subject;
    this.grade = grade;
  }


there's a little catch. 有个小陷阱!!

Unlike old-school constructor functions

To call the parent constructor we have to use the super() operator, like so:

class Teacher extends Person {
  constructor(subject, grade) {
    super(); // Now 'this' is initialized by calling the parent constructor.
    this.subject = subject;
    this.grade = grade;
  }
}

There is no point having a sub-class if it doesn't inherit properties from the parent class.   用super()才接收父类构造函数。
It is good then, that the super() operator also accepts arguments for the parent constructor.


Note: Getters and setters can be very useful at times, for example when you want to run some code every time a property is requested or set. For simple cases, however, plain property access without a getter or setter will do just fine.

class Teacher extends Person {
  constructor(first, last, age, gender, interests, subject, grade) {
    super(first, last, age, gender, interests);
    // subject and grade are specific to Teacher
    this._subject = subject;
    this.grade = grade;
  }

  get subject() {
    return this._subject;
  }

  set subject(newSubject) {
    this._subject = newSubject;
  }
}
We use _ to create a separate value in which to store our name property. Without using this convention, we would get errors every time we called get or set. At this point:


Note: Because of the way JavaScript works, with the prototype chain, etc., the sharing of functionality between objects is often called delegation. Specialized objects delegate functionality to a generic object type.

不要有太多层级关系的继承。
When using inheritance, you are advised to not have too many levels of inheritance, and to keep careful track of where you define your methods and properties

Too much inheritance can lead to endless confusion, and endless pain when you try to debug such code.

Ultimately, objects are just another form of code reuse, like functions or loops, with their own specific roles and advantages.


阅读量: 410
发布于:
修改于: