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
上面的例子中,name 被设置为了 public,所以直接访问实例的 name 属性是允许的。
很多时候,我们希望有的属性是无法直接存取的,这时候就可以用 private 了:
1 2 3 4 5 6 7 8 9 10 11 12 13
class Animal { private name; public constructor(name) { this.name = name; } }
let a = new Animal('Jack'); console.log(a.name); 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'.
var Animal = (function () { function Animal(name) { this.name = name; } return Animal; })(); var a = new Animal('Jack'); console.log(a.name); a.name = 'Tom';
使用 private 修饰的属性或方法,在子类中也是不允许访问的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class Animal { private name; public constructor(name) { this.name = name; } }
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.
当构造函数修饰为 protected 时,该类只允许被继承:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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.
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');
类的类型
给类加上 TypeScript 的类型很简单,与接口类似:
1 2 3 4 5 6 7 8 9 10 11 12
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