current position:Home>Object oriented JavaScript

Object oriented JavaScript

2022-04-29 08:09:21Chen Chen is trying

3、 ... and 、 Object oriented advanced

This section requires you to look ahead Advanced function 1、 Prototype and prototype chain Familiar with , If you don't master it well enough, it will be relatively difficult to understand

1、 Object creation pattern

Ⅰ-Object Constructor Pattern

Mode one : Object Constructor Pattern

  • tricks : Create empty first Object object , Then dynamically add attributes / Method
  • Applicable scenario : At the beginning, the internal data of the object is uncertain
  • problem : Too many sentences
/* A person : name:"Tom", age: 12*/
//  Create empty first Object object 
var p = new Object()
p = {
     } // At this time, the internal data is uncertain 
//  Then dynamically add attributes / Method 
p.name = 'Tom'
p.age = 12
p.setName = function (name) {
     
this.name = name
}

// test 
console.log(p.name, p.age)
p.setName('Bob')
console.log(p.name, p.age)

Ⅱ- Object literal pattern

Mode two : Object literal pattern

  • tricks : Use {} Create objects , Also specify the properties / Method
  • Applicable scenario : At the beginning, the internal data of the object is determined
  • problem : If you create multiple objects , There are duplicate codes
// Object literal pattern 
var p = {
     
 name: 'Tom',
 age: 12,
 setName: function (name) {
     
   this.name = name
 }
}
// test 
console.log(p.name, p.age)
p.setName('JACK')
console.log(p.name, p.age)

var p2 = {
       // If you create multiple objects, the code is repetitive 
 name: 'Bob',
 age: 13,
 setName: function (name) {
     
   this.name = name
 }
}

Ⅲ- Factory mode

Mode three : Factory mode

  • tricks : Create objects dynamically through factory functions and return
  • Applicable scenario : Multiple objects need to be created
  • problem : Object does not have a specific type , All are Object type
// Function that returns an object ===> Factory function 
function createPerson(name, age) {
      
var obj = {
     
 name: name,
 age: age,
 setName: function (name) {
     
   this.name = name
 }
}
return obj
}

//  establish 2 personal 
var p1 = createPerson('Tom', 12)
var p2 = createPerson('Bob', 13)

// p1/p2 yes Object type 

function createStudent(name, price) {
     
var obj = {
     
 name: name,
 price: price
}
return obj
}
var s = createStudent(' Zhang San ', 12000)
// s It's also Object

Ⅳ- Custom constructor mode

Mode 4 : Custom constructor mode

  • tricks : Custom constructors , adopt new Create objects
  • Applicable scenario : More than one... Needs to be created Type determination The object of , Compared with the factory mode above
  • problem : Each object has the same data , Waste of memory
  // Definition type 
  function Person(name, age) {
     
      this.name = name
      this.age = age
      this.setName = function (name) {
     
          this.name = name
      }
  }

  var p1 = new Person('Tom', 12)
  p1.setName('Jack')
  console.log(p1.name, p1.age)
  console.log(p1 instanceof Person)

  function Student(name, price) {
     
      this.name = name
      this.price = price
  }

  var s = new Student('Bob', 13000)
  console.log(s instanceof Student)

  var p2 = new Person('JACK', 23)
  console.log(p1, p2)

Ⅴ- Constructors + Combination mode of prototype

Methods five : Constructors + Combination mode of prototype –> It's best to write in this way

  • tricks : Custom constructors , Property is initialized in a function , Method is added to the prototype
  • Applicable scenario : need Create multiple types to determine The object of
  • Put it on the prototype to save space ( Just load the method once )
  // Only general functions are initialized in the constructor 
  function Person(name, age) {
     
      this.name = name
      this.age = age
  }

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

  var p1 = new Person('Tom', 23)
  var p2 = new Person('Jack', 24)
  console.log(p1, p2)

2、 Inheritance pattern

Ⅰ- Prototype chain inheritance

The way 1: Prototype chain inheritance

  1. tricks
    • Define the parent type constructor
    • Add a method to the prototype of the parent type
    • Defines the constructor for subtypes
    • Create an object of the parent type and assign it to the prototype of the child type
    • Set the construction property of the subtype prototype to subtype –> If you have doubts here, you can see this note Advanced function 1、 Prototype and prototype chain
    • Add methods to subtype prototypes
    • Create sub type objects : You can call methods of the parent type
  2. The key
    • The prototype of the subtype is an instance object of the parent type
// Parent type 
function Supper() {
     
this.supProp = ' Father's prototype chain '
}
// Add a... To the prototype of the parent type [showSupperProp] Method , Print itself subProp
Supper.prototype.showSupperProp = function () {
     
console.log(this.supProp)
}

// subtypes 
function Sub() {
     
this.subProp = ' Son's prototype chain '
}

//  The prototype of the subtype is an instance object of the parent type 
Sub.prototype = new Supper()
//  Let the prototype of the subtype constructor Point to subtypes 
//  If not , Its constructor is not found [`new Supper()`] From the top when Object Inherited constructor , Point to [`Supper()`]
Sub.prototype.constructor = Sub
// Add a... To the prototype of the subtype [showSubProp] Method , Print itself subProp
Sub.prototype.showSubProp = function () {
     
console.log(this.subProp)
}

var sub = new Sub()

sub.showSupperProp() // Father's prototype chain 
sub.showSubProp() // Son's prototype chain 
console.log(sub)  
/** Sub {subProp: " Son's prototype chain "} subProp: " Son's prototype chain " __proto__: Supper constructor: ƒ Sub() showSubProp: ƒ () supProp: " Father's prototype chain " __proto__: Object */

① figure

Be careful : Not shown in this figure [constructor Constructors ], It will be pointed out in the supplement below

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-PyeBvqpK-1650515239658)(.\JavaScript senior .assets\image-20210728101320606.png)]

② Constructors complement

For code [Sub.prototype.constructor = Sub] Is there any doubt ?

If not , Its constructor is not found [new Supper()] It's from the top Object Inherited constructor , Point to [Supper()], Although if you don't add this sentence , In general, the use is unaffected , But you have an attribute pointing to the wrong , If you are in a large project, where can you call it again ?

  1. Here we can add constructor The concept of :
  • constructor We call it constructors , Because it points back to the constructor itself
  • Its function is to make a constructor produce All instance objects ( such as f) Can find his constructor ( such as Fun), Usage is f.constructor
  1. There is no in the instance object at this time constructor This attribute , So I found it up the prototype chain Fun.prototype Inside constructor, And point to Fun The function itself
  • constructor This exists in the prototype , Pointing constructor , When you become a child , If... In the prototype chain constructor Not in itself, but in the parent prototype , So the constructor pointing to the parent class
  1. Because the inheritance here directly changes the constructor prototype The direction of , So in sub In the prototype chain of ,Sub.prototype No, constructor attribute , Instead, I saw a super example
  2. This makes sub Example of constructor Can't use . So he can use , Right there super An example is added manually constructor attribute , And point to Sub The function sees a super example

Ⅱ- Inheritance by borrowing the constructor ( fake )

The way 2: Inheritance by borrowing the constructor ( fake )

  1. tricks :
  • Define the parent type constructor
  • Define a subtype constructor
  • Calling parent type constructor in subtype constructor
  1. The key :
  • Common in subtype constructors call() Call the parent type constructor
  1. effect :
  • Can borrow the constructor in the parent class , But not flexible
function Person(name, age) {
     
this.name = name
this.age = age
}
function Student(name, age, price) {
     
// Use here call(), take  [Student] Of this Pass to Person Constructors 
Person.call(this, name, age)  //  amount to : this.Person(name, age)
/*this.name = name this.age = age*/
this.price = price
}

var s = new Student('Tom', 20, 14000)
console.log(s.name, s.age, s.price)

[Person] Medium this It's dynamic , stay [Student] In the use of [Person.call(this, name, age)] Changed its this Point to , So this effect can be achieved

Ⅲ- Combination inheritance

The way 3: Prototype chain + Borrowing the combination inheritance of constructors

  1. Using prototype chain to realize method inheritance of parent type object
  2. utilize super() Borrowing the parent type build function to initialize the same property
function Person(name, age) {
     
this.name = name
this.age = age
}
Person.prototype.setName = function (name) {
     
this.name = name
}

function Student(name, age, price) {
     
Person.call(this, name, age)  //  To get properties 
this.price = price
}
Student.prototype = new Person() //  In order to see the methods of the parent type 
Student.prototype.constructor = Student // correct constructor attribute 
Student.prototype.setPrice = function (price) {
     
this.price = price
}

var s = new Student('Tom', 24, 15000)
s.setName('Bob')
s.setPrice(16000)
console.log(s.name, s.age, s.price)

copyright notice
author[Chen Chen is trying],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/04/202204290809166587.html

Random recommended