1. 首页
  2. 考试认证
  3. 其它
  4. JavaScript面向对象编程的核心概念

JavaScript面向对象编程的核心概念

上传者: 2024-12-13 01:10:15上传 ZIP文件 202.97KB 热度 6次

JavaScript-OOP,即JavaScript面向对象编程,是JavaScript编程语言中的一个重要概念。面向对象编程(Object-Oriented Programming,简称OOP)是一种编程范式,它基于“对象”来设计软件和构建程序,允许代码以更加模块化和可重用的方式组织。在JavaScript中,OOP主要通过类和对象、封装、继承、多态这四个核心概念来实现。

  1. 类与对象

JavaScript ES6之前,由于原生不支持类的概念,我们通常使用构造函数和原型来模拟类的行为。ES6引入了class关键字,使得语法更接近传统的面向对象语言。类定义了一个模板,用于创建具有相同属性和方法的对象。对象是类的实例,它们持有数据并可以执行操作。


// ES5的构造函数

function Person(name) {

  this.name = name;

}

Person.prototype.sayName = function() {

  console.log(this.name);

}



// ES6的类

class Person {

  constructor(name) {

    this.name = name;

  }

  sayName() {

    console.log(this.name);

  }

}

  1. 封装

封装是将数据和操作这些数据的方法捆绑在一起的过程,使得数据对外部世界隐藏,减少代码间的耦合度。在JavaScript中,我们通常通过this关键字和闭包来实现封装。


class Box {

  constructor(width, height) {

    this.width = width;

    this.height = height;

  }

  getArea() {

    return this.width * this.height;

  }

}

const box = new Box(5, 4);

console.log(box.getArea()); // 20

  1. 继承

继承允许一个类(子类)从另一个类(父类)继承属性和方法,从而实现代码的复用。在ES6之前,我们通常使用原型链来实现继承;ES6引入了extends关键字,使得继承变得更加直观。


class Shape {

  constructor(color) {

    this.color = color;

  }

  setColor(color) {

    this.color = color;

  }

}



class Rectangle extends Shape {

  constructor(width, height, color) {

    super(color); //调用父类的构造函数

    this.width = width;

    this.height = height;

  }

  getArea() {

    return this.width * this.height;

  }

}

const rect = new Rectangle(5, 4, 'blue');

rect.setColor('red');

console.log(rect.color, rect.getArea()); // red 20

  1. 多态

多态是指同一种行为在不同对象上表现出不同的形式。JavaScript中的多态主要体现在函数的动态绑定上,即同一个方法根据调用它的对象的不同,可以有不同的实现。


class Animal {

  speak() {

    console.log('Animal speaks');

  }

}



class Dog extends Animal {

  speak() {

    console.log('Dog barks');

  }

}



class Cat extends Animal {

  speak() {

    console.log('Cat meows');

  }

}



const animals = [new Animal(), new Dog(), new Cat()];

animals.forEach(animal => animal.speak());

下载地址
用户评论