TypeScript 中的私有、公有和受保护访问修饰符
访问修饰符至关重要,因为它们允许我们强制执行封装并定义类成员可访问性的边界。使用访问修饰符,我们可以限制对某些成员的访问,确保它们仅在类本身内可访问。我们还可以将成员设为公共,允许它们在我们的代码库中的任何地方访问。此外,受保护的成员允许在类及其派生类中访问。
在本教程中,我们将探讨 TypeScript 中的私有、公有和受保护访问修饰符。
语法
用户可以按照以下语法在 TypeScript 中将访问修饰符应用于类成员:
class ClassName {
private propertyName: type;
public methodName(): returnType {
// Method body
}
protected anotherPropertyName: type;
}
在上述语法中:
private − 此访问修饰符将成员的访问权限限制为其声明所在的类。关键字 private 表示它。
public − 此访问修饰符允许从任何地方无限制地访问成员。如果未指定任何访问修饰符,则为默认访问修饰符。关键字 public 表示它。
protected − 此访问修饰符允许在类及其派生类中访问成员。它由关键字 protected 表示。
示例 1:公共访问修饰符
在此示例中,我们创建了一个名为 Person 的类,它具有一个公共属性 name,可以在代码中的任何地方访问和修改。我们还有一个公共方法 greet(),它使用 name 属性打印问候语。
然后,我们创建名为 Person 的 Person 类的实例。我们可以直接访问 person 对象的 name 属性并为其赋值。最后,我们在 person 对象上调用 greet() 方法,该方法输出问候语,包括 name。用户可以观察输出以查看带有提供的 name 的问候语。
class Person {
public name: string = "";
public greet(): void {
console.log(`Hello, my name is ${this.name}!`);
}
}
// Creating an instance of the Person class
const person = new Person();
// Assigning a value to the public property
person.name = "John";
// Calling the public method to display the greeting
person.greet();
编译后,它将生成以下 JavaScript 代码:
var Person = /** @class */ (function () {
function Person() {
this.name = "";
}
Person.prototype.greet = function () {
console.log("Hello, my name is ".concat(this.name, "!"));
};
return Person;
}());
// Creating an instance of the Person class
var person = new Person();
// Assigning a value to the public property
person.name = "John";
// Calling the public method to display the greeting
person.greet();
输出
以上代码将产生以下输出:
Hello, my name is John!
示例 2:私有访问修饰符
在此示例中,我们创建了一个名为 BankAccount 的类,它具有一个私有属性 balance,只能在类内访问和修改。此外,我们还有一个私有方法 calculateInterest(),它根据 balance 计算利息。
定义类后,我们创建名为 account 的 BankAccount 类的实例,初始余额为 $1000。
但是,尝试从类外部直接访问私有属性 balance 或调用私有方法 calculateInterest() 将导致错误,因为这些成员在类范围之外是不可访问的。
用户可以在输出中观察到,尝试访问私有成员将导致 TypeError。
class BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
private calculateInterest(): number {
const interestRate = 0.05;
return this.balance * interestRate;
}
}
// Creating an instance of the BankAccount class
const account = new BankAccount(1000);
// Attempting to access private members
console.log(account.balance);
console.log(account.calculateInterest());
编译后,它将生成以下 JavaScript 代码:
var BankAccount = /** @class */ (function () {
function BankAccount(initialBalance) {
this.balance = initialBalance;
}
BankAccount.prototype.calculateInterest = function () {
var interestRate = 0.05;
return this.balance * interestRate;
};
return BankAccount;
}());
// Creating an instance of the BankAccount class
var account = new BankAccount(1000);
// Attempting to access private members
console.log(account.balance);
console.log(account.calculateInterest());
它将给出以下错误:
Property 'balance' is private and only accessible within class 'BankAccount'. Property 'calculateInterest' is private and only accessible within class 'BankAccount'.
输出
以上 JavaScript 代码将产生以下输出:
1000 50
示例 3:受保护的访问修饰符
在此示例中,我们创建了一个名为 Animal 的基类,它具有一个受保护的属性 name,可以在类及其派生类中访问和修改。我们还有一个受保护的方法 makeSound(),它只记录一条消息。
然后,我们创建一个派生类 Dog,它扩展了 Animal 类。Dog 类添加了一个公共方法 bark(),它利用从基类继承的 name 属性来输出一条吠叫消息。
最后,我们创建名为 dog 的 Dog 类的实例,其名称为“Buddy”,并调用 bark() 方法。
输出将显示狗的名称,后跟吠叫消息。
class Animal {
protected name: string;
constructor(name: string) {
this.name = name;
}
protected makeSound(): void {
console.log("The animal makes a sound");
}
}
class Dog extends Animal {
public bark(): void {
console.log(`${this.name} barks!`);
}
}
// Creating an instance of the Dog class
const dog = new Dog("Buddy");
dog.bark();
编译后,它将生成以下 JavaScript 代码:
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var Animal = /** @class */ (function () {
function Animal(name) {
this.name = name;
}
Animal.prototype.makeSound = function () {
console.log("The animal makes a sound");
};
return Animal;
}());
var Dog = /** @class */ (function (_super) {
__extends(Dog, _super);
function Dog() {
return _super !== null && _super.apply(this, arguments) || this;
}
Dog.prototype.bark = function () {
console.log("".concat(this.name, " barks!"));
};
return Dog;
}(Animal));
// Creating an instance of the Dog class
var dog = new Dog("Buddy");
dog.bark();
输出
编译后,以上代码将生成一个 JavaScript 代码。JavaScript 代码将产生以下结果:
Buddy barks!
在本教程中,我们学习了 TypeScript 中的私有、公有和受保护访问修饰符。私有成员只能在类内访问,公共成员可以在任何地方访问,受保护的成员可以在类及其派生类中访问。通过使用这些访问修饰符,我们可以根据需要控制类成员的可见性和可访问性。
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP