ES5- und ES6-Methode zum Erstellen und Erben von Klassen

Klasse erstellen 

1. Erstellen Sie Klassen mit ES5

Alle Eigenschaften werden im Konstruktor platziert und alle Methoden werden auf den Prototyp geschrieben

function Obj (name,age){

    this.name = name
    this.age = age

}
Obj.protoType.sayHi = function () {

  console.log ('我是' + this.name + ',' + '年龄' + this.age)

}
var c1 = new Obj ('小明','20')

Obj.version = '1.0.1'

Obj.fn = function () {

  console.log('函数的静态方法')

}

c1.sayHi() // 可以访问原型上的方法
// c1.fn()  // 实例不允许访问静态方法
Obj.fn() // 构造函数也是对象,调用了自己的方法

2. Erstellen Sie Klassen mit ES6

Class Person {

  constructor(name,age){
     this.name = name
     this.age = age
  }

  sayHi(){
     console.log(this.name)
  }

  static fn () {
     console.log('这是构造函数的静态方法')
  }

}

var c2 = new Person ('小刘','22')
c2.sayHi()
// c2.fn()  // 实例不允许访问构造函数的静态方法

ES5, ES6 implementieren Vererbung

(1) ES5-Vererbung

function Person (name) {
  this.name = name 
}

Person.protoType.fn = function () {
  console.log(this.name)
}

function Child (c,name) {
   this.lookLike = c
   Person.call (this,name)
}

Child.protoType = Object.create(Person.protoType)
Child.protoType.constructor = Child

(2) ES6-Vererbung

Class Person {
  constructor (name) {
    this.name = name
  }
  fn () {
    console.log(this.name)
  }

}
Class Child extends Person {
  constructor (c,name) {
   super (name)
   this.lookLike = c
  }
}

おすすめ

転載: blog.csdn.net/weixin_50543490/article/details/128001597