是什么
- es6新提供的一种生成对象实例的写法 es5构造函数的另外一种写法(语法糖)
作用
回顾之前es5生成实例对象
Person.prototype.say = function(){
console.log('我会说话');
}
function Person(name,age){
this.name = name
this.age = age
}
let person1 = new Person('张三',18)
person1.say()
class类生成实例对象
class Person{
constructor(name,age){
this.name = name
this.age = age
}
say(){
console.log(`我是${this.name}`);
}
}
let person2 = new Person('李四',20)
person2.say()
console.log(typeof Person);
console.log(person2.constructor === Person);
constructor 方法
class Car{
constructor(){
console.log(this);
return Object.create(null)
}
}
let bmw = new Car()
console.log(bmw instanceof Car)
共享一个原型对象
class Person{
constructor(name) {
this.name = name
}
}
Person.prototype.get = function(){
console.log('我是父类')
}
let person1 = new Person('张三')
let person2 = new Person('李四')
person1.get()
person2.get()
取值函数和存值函数
const person = {
get name(){
console.log(name);
return name
},
set name(value){
console.log(value);
name = value
}
}
person.name = 'tony'
console.log(person.name);
class MyClass{
get prop(){
return MyClass.prop
}
set prop(value){
MyClass.prop = value
}
}
let init = new MyClass()
init.prop = 123
console.log(init.prop);
this指向问题
eat = ()=>{
this.get()
}
constructor(){
this.eat = this.eat.bind(this)
}
实例属性的新写法
class Person{
name = 'tony'
}
静态属性
class Person{
static age = 18
name = 'tony'
}
let person1 = new Person()
console.log(person1.age);
静态方法
class Person{
static age = 18
static say(){
console.log('hello');
}
name = 'tony'
}
Person.say()
私有属性
以前用闭包实现私有属性
class Math{
#count = 0
add(){
this.#count ++;
return this.#count
}
}
let math = new Math()
console.log(math.add());
私有方法
class MathAdd{
#a;
#b;
constructor(){
this.#a = 1;
this.#b = 2;
}
#sum = ()=>{
return this.#a + this.#b
}
conSum(){
console.log(this.#sum());
}
}
let mathadd = new MathAdd()
mathadd.conSum()