简介
JavaScript
作为一门弱类型的解释性语言,其既可以满足面向对象编程的需要,也可以实践函数式编程范式。随着ES
版本的演进,JavaScript
的功能越来越丰富,书写起来也越来越舒服。其中ES6
新增的Class
语法也使得JavaScript
与传统的面向对象语言越来越相似。ES6
的class
可以看作只是一个语法糖,它的绝大部分功能,ES5
都可以做到,新的class
写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。
// 分别使用ES5和ES6语法实现创建对象
function PersonES5(name, age) {
this.name = name;
this.age = age;
}
PersonES5.prototype.walk = function() {
console.log(`${
this.name} can walk!`);
}
class PersonES6 {
constructor(name, age) {
this.name = name;
this.age = age;
}
walk() {
console.log(`${
this.name} can walk!`);
}
}
console.dir(PersonES6);
console.log(`PersonES6 type is: ${
typeof PersonES6}`);
输出结果如下:
由此可见Cl