JavaScript的封装、继承和多态

在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 是基类,CircleSquare 是派生类。每个派生类都覆盖了基类的 getArea 方法,从而实现了多态。通过使用不同的派生类对象,可以调用相同的方法获得不同的结果。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值