constructor static privite

68 阅读1分钟

constructor

image.png

static

类(class)通过 static 关键字定义静态方法。不能在类的实例上调用静态方法,而应该通过类本身调用,注意:添加了static 后的方法是挂载在class对象上,去掉了static是挂载在prototype上

class Tripple {
  static tripple(n = 1) {
    return n * 3;
  }
}


let tp = new Tripple();
console.log(tp.tripple());
export default Tripple

首先分析Tripple打包出来的内容,它打包出来是一个函数,函数上有tripple对象,此时需要注意tripple静态方法是挂载在Tripple上的 image.png 如果把static去掉,看下打包效果如下所示,此时的tripple是挂在在prototype上的。tp上没有tripple方法,所以通过原型链的方式tp.proto(Tripple.prototype),如果是static方法Tripple.prototype上没有tripple方法,如果去掉了它才会有,因此,可以解释为什么在类的实例上调用净态方法是不可行的。

image.png

另外针对Tripple本身方法调用上需要注意,static 的tripple是挂在Tripple对象上,所以可以直接 Tripple.tripple()的方式调用,但是去掉static后,tripple是挂在原型Tripple.prototype上,所以可以通过原型Tripple.prototype或实例化对象new Tripple().prototype调用

image.png

image.png

private

image.png