ES6中引入了'类'这个概念,作为对象的模板。可以通过class这个关键字来定义类。用class定义的类,可以理解为对象的构造函数
1、创建实例方法如下:
1.1、基本
class Car {
constructor () {
//构造函数
}
brand () {
return 'YinLong'
}
color () {
return '#000'
}
}
let car = new Car();
console.log(car.brand())
解析:
car.constructor === Car.prototype.constructor;
1.2、借用表达式
let Car = class Me {
getBrand () {
//...
}
}
let car = new Car();
解析1:Me只在 Class 内部有定义。指代当前class定义的类。
---
let car = new class {
constructor (brand,color) {
this.brand = brand;
this.color = color;
}
}('YinLong','color');
解析2:立即执行的类实;;
2、使用class定义类的方法
class Car {
constructor (brand,color) {
// 2.1.1、添加方法
this.brand = brand;
this.color = color;
}
}
let car = new Car('YinLong','#fff');
// 2.2、判断是否存在某属性或方法
console.log(car.hasOwnProperty('color'));//true
// 2.1.2、添加方法---向原型链中添加
car.__proto__.type = 'SUV';
注意:在class类内不存在变量提升;
ES6---class
最新推荐文章于 2022-01-08 15:24:39 发布