4、对象和类

函数构造对象

使用函数构造对象通常是通过构造函数的方式。构造函数是一种特殊的函数,用于创建具有特定属性和方法的对象。

在JavaScript中,this通常指向的是我们正在执行的函数本身,或者是指向该函数所属的对象(运行时)

function Person(name, age) {
    this.name = name;
    this.age = age;
    this.greet = function() {
        console.log("Hello, my name is " + this.name);
    };
}
 
const person1 = new Person("Alice", 30);
person1.greet(); // 输出: Hello, my name is Alice

Class类

类是用于创建对象的模板。

ES6引入了类(Class)的概念,提供了一种更接近传统面向对象编程语言的语法来创建和管理对象。

我们使用 class 关键字来创建一个类,类体在一对大括号 {} 中,我们可以在大括号 {} 中定义类成员的位置,如方法或构造函数。

每个类中包含了一个特殊的方法 constructor(),它是类的构造函数,这种方法用于创建和初始化一个由 class 创建的对象。

class ClassName {
  constructor() { ... }
}
class WebSite {
  constructor(name, url) {
    this.name = name;
    this.url = url;
  }
}

创建对象

定义好类后,我们就可以使用 new 关键字来创建对象:

class Student{
    constructor(id,name){
        this.id = id
        this.name = name
    }
}

var stu = new Student('1','tom')
console.log(stu)

静态方法

类中可以使用static关键字来生成类的静态成员

注意:类的静态成员只能使用类名来调用

class Student{
    constructor(id,name){
        this.id = id
        this.name = name
    }
    static sayHello(){
        console.log('hello')
    }
}

var stu = new Student('1','tom')
console.log(stu)

Student.sayHello()

类继承

// 基类
class Animal {
    // eat() 函数
    // sleep() 函数
};
 
 
//派生类
class Dog extends Animal {
    // bark() 函数
};

函数构造对象和Class类的区别

语法差异

原型链

继承

封装和复用

原型对象

在 JavaScript 中,原型(prototype)是一个非常重要的概念,它为对象提供了继承和共享属性的机制。每个 JavaScript 对象都有一个与之关联的原型对象,通过原型对象,可以实现属性和方法的共享,从而减少内存占用。

所有的 JavaScript 对象都会从一个 prototype(原型对象)中继承属性和方法。

对象的

每个 JavaScript 对象(除了 null)都自动拥有一个隐藏的属性 __proto__,它指向该对象的原型对象。这个 __proto__ 是实现继承的关键:

let obj = {};
console.log(obj.__proto__); // 输出: [object Object], 即 obj 的原型是 Object.prototype

构造函数和原型

function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
}
 
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");