五指山市网站建设_网站建设公司_Photoshop_seo优化
2025/12/26 11:54:59 网站建设 项目流程

TypeScript对象可以被视为包含一组键值对的实例。

TypeScript映射实体时,一般将:

(1) 实体的特征、状态转为属性。

(2) 行为、功能转为函数。

TypeScript创建对象的方法一般有以下几种:

(1) 字面方式创建对象,在定义结构的同时创建对象

(2)直接创建匿名对象

(3)使用接口定义结构并创建对象

(4)用类的构造方法创建对象

1. 使用对象字面量直接创建对象

const person={ name:'张三', age:18, birthday:'2003-10-18', hobbies:['篮球','足球'], sayHello:function(){ console.log(`hello,${this.name}`); }, printfInfo:function(){ console.log(`姓名:${this.name},年龄:${this.age}`); console.log(`爱好:${this.hobbies}`); console.log(`生日:${this.birthday}`); } } console.log(person.sayHello()); console.log(person.printfInfo());

2. 直接创建匿名对象

function greet(person: { name: string; age: number }) { return "Hello " + person.name; } console.log(greet({ name: "Bob", age: 25 }));

3. 使用接口定义结构并创建对象

通过 interface 关键字,我们可以给对象类型命名,使其可以在多个地方复用。

interface Person { name: string; age: number; hobbies: string[]; } const person: Person = { name: "Alice", age: 30, hobbies: ["reading", "swimming"] }; console.log(person.hobbies);

4. 用类的构造方法创建对象

class Person { name: string; age: number; hobbies: string[]; constructor(name: string, age: number) { this.name = name; this.age = age; this.hobbies = []; } sayHello() { console.log(`hello,${this.name}`); } printfInfo() { console.log(`姓名:${this.name},年龄:${this.age}`); console.log(`爱好:${this.hobbies}`); } addHobby(hobby: string) { this.hobbies.push(hobby); } } const person1 = new Person("张三", 18); person1.addHobby('篮球'); person1.addHobby('足球'); person1.printfInfo();

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询