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

ES5 写法
function Book(title, pages, isbn) {
this.title = title;
this.pages = pages;
this.isbn = isbn;
}
Book.prototype.printTitle = function () {
console.log(this.title);
};
let book = new Book('title', 'pag', 'isbn');
console.log(book.title); //输出图书标题
book.title = 'new title'; //更新图书标题
console.log(book.title); //输出图书标题
用ES6把语法简化如下:
class Book {
constructor (title, pages, isbn) {
this.title = title;
this.pages = pages;
this.isbn = isbn;
}
printIsbn(){
console.log(this.isbn);
}
}
只需要使用class关键字,声明一个有constructor函数和诸如printIsbn等其他函数的
类。声明的代码具有相同的效果和输出:
let book = new Book('title', 'pag', 'isbn');
console.log(book.title); //输出图书标题
book.title = 'new title'; //更新图书标题
console.log(book.title); //输出图书标题
 
 
继承
除了新的声明类的方式,类的继承也有简化的语法。我们看一个例子:
class ITBook extends Book {
constructor (title, pages, isbn, technology) {
super(title, pages, isbn);
this.technology = technology;
}
printTechnology(){
console.log(this.technology);
}
}
let jsBook = new ITBook('学习JS算法', '200', '1234567890', 'JavaScript');
console.log(jsBook.title);
console.log(jsBook.printTechnology());
我们可以用extends关键字扩展一个类并继承它的行为。在构造函数中,我们也
可以通过super关键字引用父类的构造函数
尽管在JavaScript中声明类的新方式的语法与Java、 C、 C++等其他编程语言很类似,但
JavaScript面向对象编程还是基于原型实现的

猜你喜欢

转载自www.cnblogs.com/zhaofeis/p/10598850.html
今日推荐