在 JavaScript 中,构造函数是实现面向对象编程的关键工具之一。它与 this
关键字、箭头函数的作用域链以及原型和原型链紧密相关。本文将全面深入地探讨 JavaScript 构造函数的各个方面。
一、构造函数的定义与用法
构造函数是一种特殊的函数,用于创建对象。其名称通常以大写字母开头,以区别于普通函数。例如:
function Person(name, age) {
this.name = name;
this.age = age;
}
使用 new
关键字调用构造函数可以创建对象实例。例如:
let person1 = new Person('Alice', 30);
let person2 = new Person('Bob', 25);
console.log(person1); // { name: 'Alice', age: 30 }
console.log(person2); // { name: 'Bob', age: 25 }
二、构造函数的特性
(一)创建对象实例
当使用 new
调用构造函数时,会自动创建一个新对象,在构造函数内部通过 this
引用该对象。
(二)属性初始化
构造函数可以接受参数来初始化对象的属性,根据不同输入创建具有不同属性值的对象。例如:
function Rectangle(width, height) {
this.width = width;
this.height = height;
}
const rect = new Rectangle(5, 10);
console.log(rect); // { width: 5, height: 10 }
(三)方法继承
可以在构造函数内部定义方法,这些方法会被创建的对象实例继承。例如:
function Animal(name) {
this.name = name;
this.sayName = function() {
console.log(`My name is ${this.name}.`);
};
}
const animal = new Animal('Cat');
animal.sayName(); // My name is Cat
(四)原型共享
每个构造函数都有一个 prototype
属性指向原型对象,原型对象上的属性和方法可被该构造函数创建的所有对象实例共享。例如:
function Person() {}
Person.prototype.sayHello = function() {
console.log('Hello!');
};
const person1 = new Person();
const person2 = new Person();
person1.sayHello(); // Hello!
person2.sayHello(); // Hello!
(五)可扩展性
通过在构造函数的原型上添加属性和方法,可以扩展对象,无需修改构造函数本身。例如:
function Shape() {}
Shape.prototype.draw = function() {
console.log('Drawing a shape.');
};
function Circle() {}
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;
Circle.prototype.drawCircle = function() {
console.log('Drawing a circle.');
};
const circle = new Circle();
circle.draw(); // Drawing a shape.
circle.drawCircle(); // Drawing a circle.