一 、函数构造器:
通过构造函数创建类,使用 function 关键字定义一个函数,并在该函数中定义属性和方法。通过 new 关键字实例化对象。
function Person(name, age) {
this.name = name;
this.age = age;
this.sayHello = function() {
console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
};
}
var person1 = new Person("Alice", 30);
person1.sayHello(); // Output: Hello, my name is Alice and I am 30 years old.
二、原型链继承:
通过修改原型链来实现类的继承。
// 定义 Person 类
function Person(name, age) {
this.name = name;
this.age = age;
}
// 在 Person 原型上添加方法
Person.prototype.introduce = function() {
return "Hello, my name is " + this.name + " and I am " + this.age + " years old.";
}
// 定义 Student 类,继承自 Person
function Student(name, age, grade) {
Person.call(this, name, age); // 调用父类构造函数
this.grade = grade;
}
// 设置 Student 的原型为一个新的 Person 实例
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student; // 修正构造函数指向
// 在 Student 原型上添加额外的方法
Student.prototype.study = function() {
return this.name + " is studying in grade " + this.grade + ".";
}
// 创建 Person 实例
var person1 = new Person("John", 25);
console.log(person1.introduce()); // 输出 "Hello, my name is John and I am 25 years old."
// 创建 Student 实例
var student1 = new Student("Alice", 20, 12);
console.log(student1.introduce()); // 输出 "Hello, my name is Alice and I am 20 years old."
console.log(student1.study()); // 输出 "Alice is studying in grade 12."
三、ES6 类:
使用 ES6 引入的类语法创建类,使用 class 关键字定义类,并使用 constructor 方法定义构造函数,以及其他方法。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const person1 = new Person("Charlie", 20);
person1.sayHello(); // Output: Hello, my name is Charlie and I am 20 years old.```