js之对象

一、普通对象

通过class创建对象,对象里属性、普通方法和有构造方法,然后用extends继承

// 创建一个对象,并定义其属性和方法。
class Person {
  name: string
  age: number
  // 构造函数
  constructor(name: string, age: number) {
    this.name = name
    this.age = age
  }
  // 普通方法
  speak() {
    console.log(`我的名字叫:${this.name} 年龄是 ${this.age} 岁了`)
  }
}
// 继承
class Student extends Person {
  // 构造函数
  constructor(name: string, age: number) {
    super(name, age)
  }
  // 普通方法
  study() {
    console.log(`${this.name} 正在学习`)
  }
}
const student = new Student('小明', 18)
student.speak()

 二、abstract抽象类

抽象类使用修饰词abstract定义,是一种无法被实例化的类,专门用于定义类的结构和行为,类中可以写抽象方法,也可以写普通方法。

主要用来为其派生类提供一个基础结构,要求其派生类必须实现其中的抽象方法,可以被继承。

// 抽象类
abstract class Animal {
    constructor(name: string) {
      this.name = name
    }
    name: string
    // 抽象方法, 没有实现体,即没有大括号{}
    abstract speak(): void
    // 普通方法
    eat() {
      console.log(`${this.name} 正在吃东西`)
    }
}
class Dog extends Animal { constructor(name: string) { super(name) }
// 抽象方法的实现,派生类Dog是抽象类Animal的子类,所以必须实现speak方法,即派生类必须实现其中的抽象方法 // 抽象类Animal的普通方法eat不用必须实现 speak() { console.log(`${this.name} 正在汪汪叫`) } }

 三、interface接口

interface接口是一个定义结构的方式,主要作用是为了类、对象、函授等规定的一种契约,确保代码的一致性和类型安全,只能定义格式,不能包含任何实现

1)定义类结构

// 接口
interface companyInterface {
  name: string
  addree: string
  makeMoney(): void
}
// companyInterface定义了类结构,类Company实现了companyInterface接口
class Company implements companyInterface {
  name: string
  addree: string
  constructor(name: string, addree: string) {
    this.name = name
    this.addree = addree
  }
  makeMoney() {
    console.log(`${this.name} 公司挣钱`)
  }
}

2)定义对象结构

// 定义对象结构
interface User {
  name: string
  age: number
  speak(): void
}
const user: User = {
  name: '小明',
  age: 18,
  speak() {
    console.log(`${this.name} 正在说话`)
  }
}

3)定义函授结构

interface add {
  (a: number, b: number): number // 定义了a和b的参数类型,返回值为number
}
const add: add = (a: number, b: number): number => {
  return a + b
}

4)接口之间的继承

// 接口之间的继承
interface Animal {
  name: string
  eat(): void
}
interface Dog extends Animal {
  speak(): void
}
// 使用继承
const D: Dog = {
  name: '小黑',
  eat() {
    console.log(`${this.name} 正在吃东西`)
  },
  speak() {
    console.log(`${this.name} 正在汪汪叫`)
  }
}

5)接口自动合并(可重复定义)

// 接口自动合并(可重复定义)
interface AnimalInterface {
  name: string
  eat(): void
}
interface AnimalInterface {
  age: number
  speak(): void
}
const ani: AnimalInterface = { // 上面两个AnimalInterface合并
  name: '小黑',
  age: 18,
  eat() {
    console.log(`${this.name} 正在吃东西`)
  },
  speak() {
    console.log(`${this.name} 正在汪汪叫`)
  }
}

 

posted @ 2025-03-18 10:11  zzwlong  阅读(15)  评论(0)    收藏  举报