MST

星途 面试题库

面试题:TypeScript 中类的静态成员与实例成员的区别

请详细阐述 TypeScript 中类的静态成员与实例成员在定义方式、访问方式、作用域等方面有哪些区别,并举例说明。
26.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

定义方式

  • 静态成员:在类中使用 static 关键字来定义静态成员。例如:
class MyClass {
    static staticProperty: string = '静态属性';
    static staticMethod(): void {
        console.log('这是静态方法');
    }
}
  • 实例成员:普通定义,无需 static 关键字。例如:
class MyClass {
    instanceProperty: string;
    constructor(value: string) {
        this.instanceProperty = value;
    }
    instanceMethod(): void {
        console.log(`实例属性值为: ${this.instanceProperty}`);
    }
}

访问方式

  • 静态成员:通过类名直接访问,无需创建类的实例。例如:
console.log(MyClass.staticProperty); 
MyClass.staticMethod(); 
  • 实例成员:必须先创建类的实例,然后通过实例来访问。例如:
let myInstance = new MyClass('实例值');
console.log(myInstance.instanceProperty); 
myInstance.instanceMethod(); 

作用域

  • 静态成员:静态成员的作用域是类本身,所有实例共享这些静态成员。无论创建多少个类的实例,静态成员只有一份。例如:
class Counter {
    static count: number = 0;
    constructor() {
        Counter.count++;
    }
}
let counter1 = new Counter();
let counter2 = new Counter();
console.log(Counter.count); 
  • 实例成员:实例成员的作用域是每个类的实例,每个实例都有自己独立的一套实例成员。例如:
class Person {
    name: string;
    constructor(n: string) {
        this.name = n;
    }
}
let person1 = new Person('Alice');
let person2 = new Person('Bob');
console.log(person1.name); 
console.log(person2.name); 

综上所述,静态成员和实例成员在定义、访问和作用域上都有明显的区别,在实际编程中需根据具体需求正确使用。