使用类进行面向对象编程 Class 实例化 和 ES5实例化 对比,继承

ES5 写法

// 使用构造函数和原型创建Book类
function Book(title, pages, isbn) {
    this.title = title;
    this.pages = pages;
    this.isbn = isbn;
}

// 在原型上添加printTitle方法
Book.prototype.printTitle = function () {
    console.log(this.title);
};

// 创建一个Book实例
let book = new Book('title', 'pag', 'isbn');

// 输出图书标题
console.log(book.title);

// 更新图书标题
book.title = 'new title';
console.log(book.title); // 输出图书标题

ES6 写法

// 使用ES6 class语法声明Book类
class Book {
    constructor(title, pages, isbn) {
        this.title = title;
        this.pages = pages;
        this.isbn = isbn;
    }

    // 在类中添加printIsbn方法
    printIsbn() {
        console.log(this.isbn);
    }
}

// 创建一个Book实例
let book = new Book('title', 'pag', 'isbn');

// 输出图书标题
console.log(book.title);

// 更新图书标题
book.title = 'new title';
console.log(book.title); // 输出图书标题

继承

// 使用extends关键字扩展Book类创建ITBook类
class ITBook extends Book {
    constructor(title, pages, isbn, technology) {
        // 使用super关键字调用父类的构造函数
        super(title, pages, isbn);
        this.technology = technology;
    }

    // 在子类中添加printTechnology方法
    printTechnology() {
        console.log(this.technology);
    }
}

// 创建一个ITBook实例
let jsBook = new ITBook('学习JS算法', '200', '1234567890', 'JavaScript');

// 输出图书标题
console.log(jsBook.title);

// 输出技术信息
jsBook.printTechnology();

我们可以用extends关键字扩展一个类并继承它的行为。在构造函数中,我们也可以通过super关键字引用父类的构造函数

尽管在JavaScript中声明类的新方式的语法与Java、 C、 C++等其他编程语言很类似,但JavaScript面向对象编程还是基于原型实现的

posted on 2019-03-26 11:03  完美前端  阅读(135)  评论(0)    收藏  举报

导航