class语法理解,静态、实例、原型

114 阅读1分钟

1、静态属性方法,实例属性方法,原型属性方法

class Person {
  static staticProp = "静态属性staticProp"
  static staticMethod() {
    console.log("静态方法staticMethod")
  }
  exampleCountry = "实例属性exampleCountry"
  examplePlanet = "实例属性examplePlanet"
  constructor(name, age) {
    this.name = name
    this.age = age
  }
  exampleMethod = () => {
    // 实例方法
    console.log("实例方法examplesMethod")
  }
  prototypeMethod() {
    // 原型方法 Test.prototype.prototypeMethod
    console.log("原型方法prototypeMethod")
  }
}
Person.staticProp2 = "静态属性staticProp2"
Person.staticMethod2 = "静态方法staticMethod2"
Person.prototype.prototypeProp = "原型属性prototypeProp"
Person.prototype.prototypeMethod2 = "原型方法prototypeMethod2"

const tom = new Person("Tom", 18)
console.log(tom)

tom image.png

tom隐式原型 image.png

Person的原型 image.png

tom.__proto__ === Person.prototype // true
Person.prototype.__proto__ === Object.prototype // true
Object.prototype.__proto__ === null // true

Person image.png

image.png

static静态方法中的this只能调用其他的静态属性或方法,不能调用原型方法

class的修饰符,readonly、private、pretected、public

例题1,说出代码运行输出的值

class VFront {
  a = 1
  b = 2
  name = "tom"
  age = 20
  constructor(name, age) {
    this.name = name
    this.age = age
  }
  foo() {
    console.log("foo-name:", this)
    console.log(this.name)
  }
  bar = () => {
    console.log("bar.name:", this)
    console.log(this.name)
  }
}

const nv = new VFront("bob", 8)
const foo = nv.foo
const bar = nv.bar
foo() // 因为用的const所以window.foo为undefined
// undefined   // 这点要注意
// Uncaught TypeError: Cannot read properties of undefined (reading 'name')

nv.foo()
// foo-name: VFront {a: 1, b: 2, name: 'bob', age: 8, bar: ƒ}
// bob


bar() // new的时候初始化的bar,bar是箭头函数,this始终指向新生成的对象
// bar.name: VFront {a: 1, b: 2, name: 'bob', age: 8, bar: ƒ}
//bob

例题2,说出代码运行输出的值


class A {
  x = () => {
    console.log(this, 11)
  }
  y() {
    console.log(this, 22)
  }
}

const B = function () {}
B.prototype.x = () => {
  console.log(this, 66) // 定义的时候this为window
}
B.prototype.y = function () {
  console.log(this, 88)
}

const a = new A()
const b = new B()

a.x() //A {x:f} 11
a.y() //A {x:f} 22

b.x() // window 66
b.y() // B {} 88