SoFunction
Updated on 2025-04-08

A preliminary study on JavaScript object-oriented (recommended)

Class declaration

1. Constructor

function Animal() {
  = 'name'
}
// Instantiationnew Animal()

2. ES6 class

class Animal {
 constructor() {
   = 'name'
 }
}
// Instantiationnew Animal()

Inheritance of classes

1. Implement inheritance with the help of constructors

Principle: Change the point of this point at the runtime of the subclass, but the properties on the parent class prototype chain are not inherited, and are incomplete inheritance.

function Parent() {
  = 'Parent'
}
 = function(){
 ('hello')
}
function Child() {
 (this)
  = 'Child'
}
(new Parent())
(new Child())

2. Use prototype chain to achieve inheritance

Principle: Prototype chain, but in one subclass instance changes the attribute in the parent class, the attribute in other instances will also change the child, which is also incomplete inheritance.

function Parent() {
  = 'Parent'
  = [1, 2, 3]
}
 = function(){
 ('hello')
}
function Child() {
  = 'Child'
}
 = new Parent()
let s1 = new Child()
let s2 = new Child()
(4)
(, )
(new Parent())
(new Child())
(new Child().say())

3. Constructor + Prototype Chain

Best Practices

// Parent classfunction Parent() {
  = 'Parent'
  = [1, 2, 3]
}
 = function(){
 ('hello')
}
// Subclassfunction Child() {
 (this)
  = 'Child'
}
// Avoid executing the parent constructor twice, and share a constructor// But it is impossible to distinguish which constructor the instance belongs to//  = 
// Improvement: Create an intermediate object and then modify the constructor of the subclass = ()
 = Child
// Instantiationlet s1 = new Child()
let s2 = new Child()
let s3 = new Parent()
(4)
(, ) // [1, 2, 3, 4] [1, 2, 3]
() // Child
() // Parent
(new Parent())
(new Child())
(new Child().say())

Summarize

The above is the relevant knowledge about JavaScript object-oriented (recommended) introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time!