Classes

Classes are a new feature in ES6, used to describe the blueprint of an object and make EcmaScript's prototypical inheritance model function more like a traditional class-based language.

  1. class Hamburger {
  2. constructor() {
  3. // This is the constructor.
  4. }
  5. listToppings() {
  6. // This is a method.
  7. }
  8. }

Traditional class-based languages often reserve the word this to reference the current (runtime) instance of the class. In Javascript this refers to the calling context and therefore can change to be something other than the object.

Object

An object is an instance of a class which is created using the new operator. When using a dot notation to access a method on the object, this will refer to the object to the left of the dot.

  1. let burger = new Hamburger();
  2. burger.listToppings();

In the snippet above, whenever this is used from inside class Hamburger, it will refer to object burger.

Changing Caller Context

JavaScript code can optionally supply this to a method at call time using one of the following.

  • Function.prototype.call(object [,arg, …])
  • Function.prototype.bind(object [,arg, …])
  • Function.prototype.apply(object [,argsArray])

原文: https://angular-2-training-book.rangle.io/handout/features/classes.html