在JavaScript中,封装、继承和多态是面向对象编程的三个基本概念。下面是一个简单的例子,演示如何在JavaScript中实现这些概念:
封装:
封装是将对象的状态和行为捆绑在一起,并对外部隐藏其实现细节的概念。在JavaScript中,可以使用闭包和函数来实现封装。
// 使用闭包实现封装
function Person(name, age) {
let _name = name;
let _age = age;
// 对外提供访问私有属性的方法
this.getName = function() {
return _name;
};
this.getAge = function() {
return _age;
};
this.sayHello = function() {
console.log(`Hello, my name is ${_name} and I am ${_age} years old.`);
};
}
// 创建一个Person对象
let person = new Person("John", 25);
// 外部无法直接访问私有属性
console.log(person._name); // undefined
// 通过公有方法访问私有属性
console.log(person.getName()); // John
console.log(person.getAge()); // 25
// 调用对象的方法
person.sayHello(); // Hello, my name is John and I am 25 years old.
继承:
继承是通过一个对象获取另一个对象的属性和方法的机制。在JavaScript中,可以使用原型链实现继承。
// 基类
function Animal(name) {
this.name = name;
}
// 派生类
function Dog(name, breed) {
Animal.call(this, name); // 调用基类构造函数
this.breed = breed;
}
// 设置原型链
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
// 派生类的方法
Dog.prototype.bark = function() {
console.log("Woof! Woof!");
};
// 创建一个Dog对象
let myDog = new Dog("Buddy", "Golden Retriever");
// 调用继承的属性和方法
console.log(myDog.name); // Buddy
myDog.bark(); // Woof! Woof!
多态:
多态是同一操作作用于不同的对象上时产生不同的行为。在JavaScript中,通过覆盖基类的方法来实现多态。
// 基类
function Shape() {
}
// 派生类1
function Circle(radius) {
this.radius = radius;
}
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;
// 派生类2
function Square(side) {
this.side = side;
}
Square.prototype = Object.create(Shape.prototype);
Square.prototype.constructor = Square;
// 基类方法
Shape.prototype.getArea = function() {
throw new Error("This method should be overridden by subclasses");
};
// 派生类1方法
Circle.prototype.getArea = function() {
return Math.PI * Math.pow(this.radius, 2);
};
// 派生类2方法
Square.prototype.getArea = function() {
return Math.pow(this.side, 2);
};
// 使用多态
let shapes = [new Circle(5), new Square(4)];
shapes.forEach(function(shape) {
console.log(shape.getArea());
});
在上述例子中,Shape
是基类,Circle
和 Square
是派生类。每个派生类都覆盖了基类的 getArea
方法,从而实现了多态。通过使用不同的派生类对象,可以调用相同的方法获得不同的结果。