ES6
Class类
es6引入了类Class 的概念,作为对象的模板。可以使用Class关键字定义类,通过类实例化对象。
Class类可以看做是一个语法糖,绝大部分功能也可以通过es5做到。
Class写法只是让对象原型的写法更加清晰、更像面向对象变成的语法而已。
ES5 构造函数实例化对象
function Phone(brand, price) {
this.brand = brand;
this.price = price;
}
Phone.prototype.call = function () {
console.log('call me');
};
let HW = new Phone('huawei', 9999);
console.log(HW);
class声明类
构造方法 名称不能修改 实例化是自动执行
方法定义不能使用ES5对象的形式
class Phone {
// 构造方法 名称不能修改 实例化是自动执行
constructor(brand, price) {
this.brand = brand;
this.price = price;
}
// 不能使用ES5对象的形式
// call: function (){} // 错误
call() {
console.log('call me');
}
}
let OPPO = new Phone('oppo', 6666);
console.log(OPPO);
static定义静态属性、方法
es5 函数对象与实例对象属性/方法不通,通过prototype链接
function Phone() {
}
Phone.name = 'hw';
Phone.call = function () {
console.log('call me');
};
Phone.prototype.size = 10;
var hw = new Phone();
console.log(hw.name);
console.log(hw.size);
console.log(hw.call());
静态属性、方法
class Phone {
static name = 'hw';
static call() {
console.log('call me');
}
}
const hw = new Phone();
console