2022了还在用function写构造函数?来试试class吧

147 阅读2分钟

前言

很多时候我们都习惯用es5的function去写构造函数,但用es6的class的时候很多时候都写不出function的写法,下面就用这两种方式去写一些常见的场景

最常见的写法

// es5写法
function Parent(name, age){
    this.name = name;。
    this.age = age;
}

Parent.prototype.setAge = function(){
    this.age = age
}

// es6写法
class Parent{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
    setAge(){
        this.age = age;
    }
}

getter, setter(拦截器)

// es5中构造函数不存在getter,setter,不过对象中是有的
const parent = {
    name: '',
    age: '',
    get _name(){
        return this.name
    },
    set _name(name){
        this.name = 'setName'
    }
}

parent._name = 1;
console.log(parent.name);   // setName

// es6写法
class Parent{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
    setAge(){
        this.age = age;
    }
    get _name(){
        return this.name;
    }
    set _name(name){ 
        this.name = 'setName'
    }
}

const parent = new Parent();
parent._name = 1; 
console.log(parent.name);  // setName

静态属性和方法

其实相当于类上的一个属性,这个实用场景不多,只能通过类.属性方式去访问,在类里面也无法通过this去访问

//es5
function Parent() {
  
}

Parent.property = 'hello';
Parent.sayHello = function(){
    return this.property;
}

console.log(Parent.property) // 'hello'
Parent.sayHello()  // undefined

var parent = new Parent();
console.log(parent.property);  //undefined
parent.sayHello();
// TypeError: parent.sayHello is not a function

//es6
class Parent {
  static property = 'hello'
  static sayHello() {
    return this.property;
  }
}

console.log(Parent.property) // 'hello'
Parent.sayHello() // undefined, 静态属性无法通过this去访问,this.property访问不到

var parent = new Parent();
console.log(parent.property);  //undefined
parent.sayHello();
// TypeError: parent.sayHello is not a function

私有属性和方法

这个是很实用的,但你想在类里面声明变量或者方法,既不想这些变量或方法被继承,又想让这些方法和属性在类里面可以通过this去调用,主要是在变量或方法前加上#

// es5
function Parent() {
  const property = 'hello'
  this.sayHello = () =>{
    return property;
  }
}

console.log(Parent.property)   // undefined
Parent.sayHello()   // Parent.sayHello is not a function

const parent = new Parent();
console.log(parent.property);   // undefined
parent.sayHello();   // 'hello'

// es6
class Parent {
  constructor(){
    this.sayHello = () => {
        return this.#property;
    }
  }
  #property = 'hello'
  #sayHello() {
    return this.#property;
  }
  
}

//console.log(Parent.#property) // Uncaught SyntaxError: Private field '#property' must be declared in an enclosing class
//Parent.#sayHello() // Uncaught SyntaxError: Private field '#property' must be declared in an enclosing class

var parent = new Parent();
//console.log(parent.#property);  //Uncaught SyntaxError: Private field '#property' must be declared in an enclosing class
//parent.#sayHello();   //Uncaught SyntaxError: Private field '#property' must be declared in an enclosing class

parent.sayHello();   // 'hello'

如果直接去访问类里的私有属性或者方法都会直接报错,只有在类里面才能访问