TypeScript- primary class -05-

class

In the conventional method, JavaScript class concept implemented by the constructor, by means of the prototype implementation inheritance chain. In ES6, we finally ushered in class.

TypeScript addition to implementing the functional classes in all ES6, it also adds some new usage.

This section describes the use of the class, and then the next section describes how to define the type of class.

The concept of class

Although the concept of class in JavaScript, but it is likely that most JavaScript programmers are not very familiar with the class, here to do a simple introduction to the class of related concepts.

  • Class (Class): defines the abstract characteristics of a thing, it contains properties and methods
  • Object (Object): instance of a class by newgenerating
  • Object Oriented (OOP) three properties: encapsulation, inheritance, polymorphism
  • Package (Encapsulation): details of the operation of the data will be hidden and only exposed to the external interface. The outside world does not need to call the end (and can not) know the details, will be able to access the object through the interface provided externally, but also ensure that the outside world can not arbitrarily change the object's internal data
  • Inheritance (Inheritance): subclass inherits the parent class, subclass addition to all the features of the parent class, there are some more specific features
  • Polymorphism (Polymorphism): generated by a succession of different classes related, may have different responses to the same method. For example, Catand Dogare inherited from Animal, but are to achieve their eatmethods. At this time, for one example, we need to understand it is Catstill Dog, you can directly call the eatmethod, the program will automatically determine how it should be executedeat
  • Accessor (getter & setter): to change the properties and the assignment of reading behavior
  • Modifiers (Modifiers): modifier are some keywords, for defining the nature or type of member. For example publicrepresents the public properties or methods
  • Abstract (Abstract Class): abstract class is inherited by other classes of base class is instantiated abstract class is not allowed. Abstract class abstract method must be implemented in a subclass
  • Interface (Interfaces): public properties or methods of different classes, can be abstracted into a single interface. Interface may be implemented class (implements). A class can inherit from another class, but can implement multiple interfaces

ES6 usage in class

Let us first review the usage class ES6, more detail can refer to [ECMAScript 6 Getting Started - Class].

Properties and Methods

Using classthe definition of the class, using constructorthe definition of the constructor.

By newthe time generating a new instance, it will automatically call the constructor.

class Animal {
    constructor(name) {
        this.name = name;
    }
    sayHi() {
        return `My name is ${this.name}`;
    }
}

let a = new Animal('Jack');
console.log(a.sayHi()); // My name is Jack

Class inheritance

Use extendskeywords implementation inheritance, the subclass use superkeywords to call the constructor and methods of the parent class.

class Cat extends Animal {
    constructor(name) {
        super(name); // 调用父类的 constructor(name)
        console.log(this.name);
    }
    sayHi() {
        return 'Meow, ' + super.sayHi(); // 调用父类的 sayHi()
    }
}

let c = new Cat('Tom'); // Tom
console.log(c.sayHi()); // Meow, My name is Tom

Accessor

Using getter and setter can change the assignment of reading behavior and attributes:

class Animal {
    constructor(name) {
        this.name = name;
    }
    get name() {
        return 'Jack';
    }
    set name(value) {
        console.log('setter: ' + value);
    }
}

let a = new Animal('Kitty'); // setter: Kitty
a.name = 'Tom'; // setter: Tom
console.log(a.name); // Jack

Static method

Use staticmodifier modified method is called static methods, they do not need to instantiate, but directly invoked by category:

class Animal {
    static isAnimal(a) {
        return a instanceof Animal;
    }
}

let a = new Animal('Jack');
Animal.isAnimal(a); // true
a.isAnimal(a); // TypeError: a.isAnimal is not a function

ES7 usage in class

ES7 There are some proposals on the class, TypeScript also achieved them here to do a brief introduction.

Instance Properties

ES6 only by the properties in Example constructor this.xxxdefined, ES7 proposals can be directly inside the class definition:

class Animal {
    name = 'Jack';

    constructor() {
        // ...
    }
}

let a = new Animal();
console.log(a.name); // Jack

Static properties

ES7 proposal, can be used staticto define a static property:

class Animal {
    static num = 42;

    constructor() {
        // ...
    }
}

console.log(Animal.num); // 42

TypeScript usage in class

public private 和 protected

TypeScript can use three access modifiers (Access Modifiers), respectively public, privateand protected.

  • publicModified property or method is public and can be accessed from anywhere, all the default properties and methods are publicof
  • private Modified property or method is private and can not be accessed in a statement outside of its class
  • protectedModified property or method is protected, and it is privatesimilar, except that it is allowed in a subclass to be accessed

Here are some examples:

class Animal {
    public name;
    public constructor(name) {
        this.name = name;
    }
}

let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';
console.log(a.name); // Tom

In the above example, nameit is provided for public, so that direct access to the instance nameattribute is permissible.

Many times, we hope that some properties are not directly accessible, this time you can use privatethe:

class Animal {
    private name;
    public constructor(name) {
        this.name = name;
    }
}

let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';

// index.ts(9,13): error TS2341: Property 'name' is private and only accessible within class 'Animal'.
// index.ts(10,1): error TS2341: Property 'name' is private and only accessible within class 'Animal'.

Note that, after the code compilation TypeScript, not restricted privateattributes externally accessible.

The above examples are compiled code:

var Animal = (function () {
    function Animal(name) {
        this.name = name;
    }
    return Animal;
}());
var a = new Animal('Jack');
console.log(a.name);
a.name = 'Tom';

Using the privatemodified property or method in the subclass is not allowed access:

class Animal {
    private name;
    public constructor(name) {
        this.name = name;
    }
}

class Cat extends Animal {
    constructor(name) {
        super(name);
        console.log(this.name);
    }
}

// index.ts(11,17): error TS2341: Property 'name' is private and only accessible within class 'Animal'.

And if it is a protectedmodification, access is granted in a subclass:

class Animal {
    protected name;
    public constructor(name) {
        this.name = name;
    }
}

class Cat extends Animal {
    constructor(name) {
        super(name);
        console.log(this.name);
    }
}

When the modification to the constructor private, the class is not allowed to be inherited or instantiated:

class Animal {
    public name;
    private constructor (name) {
        this.name = name;
  }
}
class Cat extends Animal {
    constructor (name) {
        super(name);
    }
}

let a = new Animal('Jack');

// index.ts(7,19): TS2675: Cannot extend a class 'Animal'. Class constructor is marked as private.
// index.ts(13,9): TS2673: Constructor of class 'Animal' is private and only accessible within the class declaration.

When the constructor is modified protected, the class may only be inherited:

class Animal {
    public name;
    protected constructor (name) {
        this.name = name;
  }
}
class Cat extends Animal {
    constructor (name) {
        super(name);
    }
}

let a = new Animal('Jack');

// index.ts(13,9): TS2674: Constructor of class 'Animal' is protected and only accessible within the class declaration.

Modifiers may also be used in the constructor parameter equivalent to the attributes defined in the class, it makes the code more compact.

class Animal {
    // public name: string;
    public constructor (public name) {
        this.name = name;
    }
}

readonly

Read-only attribute keyword, only allowed in property declaration or index signature.

class Animal {
    readonly name;
    public constructor(name) {
        this.name = name;
    }
}

let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';

// index.ts(10,3): TS2540: Cannot assign to 'name' because it is a read-only property.

Note that if readonlyother access modifier exist, then, need to write behind it.

class Animal {
    // public readonly name;
    public constructor(public readonly name) {
        this.name = name;
    }
}

Abstract class

abstract For defining abstract classes and abstract methods therein.

What is an abstract class?

First, the abstract class is allowed to be instantiated:

abstract class Animal {
    public name;
    public constructor(name) {
        this.name = name;
    }
    public abstract sayHi();
}

let a = new Animal('Jack');

// index.ts(9,11): error TS2511: Cannot create an instance of the abstract class 'Animal'.

In the above example, we define an abstract class Animal, and defines an abstract method sayHi. In the example of time given the abstract class.

Secondly, abstract methods abstract class must implement subclasses:

abstract class Animal {
    public name;
    public constructor(name) {
        this.name = name;
    }
    public abstract sayHi();
}

class Cat extends Animal {
    public eat() {
        console.log(`${this.name} is eating.`);
    }
}

let cat = new Cat('Tom');

// index.ts(9,7): error TS2515: Non-abstract class 'Cat' does not implement inherited abstract member 'sayHi' from class 'Animal'.

In the above example, we define a class that Catinherits the abstract class Animal, but does not implement the abstract method sayHi, the compiler being given.

The following is an example of proper use of the abstract class:

abstract class Animal {
    public name;
    public constructor(name) {
        this.name = name;
    }
    public abstract sayHi();
}

class Cat extends Animal {
    public sayHi() {
        console.log(`Meow, My name is ${this.name}`);
    }
}

let cat = new Cat('Tom');

In the above example, we achieved an abstract method sayHi, the compiler passed.

Note that, even if the method is abstract, compile the results of TypeScript, there would still be this class, compiled the results of the above code is:

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Animal = (function () {
    function Animal(name) {
        this.name = name;
    }
    return Animal;
}());
var Cat = (function (_super) {
    __extends(Cat, _super);
    function Cat() {
        _super.apply(this, arguments);
    }
    Cat.prototype.sayHi = function () {
        console.log('Meow, My name is ' + this.name);
    };
    return Cat;
}(Animal));
var cat = new Cat('Tom');

Type of class

TypeScript add to the class type is very simple, and the interface is similar:

class Animal {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    sayHi(): string {
      return `My name is ${this.name}`;
    }
}

let a: Animal = new Animal('Jack');
console.log(a.sayHi()); // My name is Jack

Guess you like

Origin www.cnblogs.com/idspring/p/11784735.html