1. Prototype exercises

function fun() {
    this.a = 0
    this.b = function() {
        alert(this.a)
    }
}

// Prototype redirect
fun.prototype = {
    b: function() {
        this.a = 20
        alert(this.a)
    },
    c: function() {
        this.a = 30
        alert(this.a)
    }
}
var my_fun = new fun()
my_fun.b()
my_fun.c()
Copy the code
  • Prototype redirection

    • Advantage:

      • 1. The common properties and methods provided by the prototype as examples are all written together to improve the overall modularity of the latter

      • 2. It would be easier to extend the method to its prototype

    • Disadvantages:

      • 1. The prototype object after redirection is missingconstructorAttribute, solve:
      xxx.prototype = {
          // Set one manually to ensure structural integrity
          constructor: xxx
      }
      Copy the code
      • 2. If the original built-in prototype object has some properties and methods, then after redirection, the previously set public property method will be lost.
      xxx.prototype = Object.assign(xxx.prototype,{
          // Public properties and methods
      })
      Copy the code

1.

  • Object.assign: Merge two objects “shallow comparison”

    • Replace the contents of obj2 with the contents of obj1: both have the main contents of obj2, only one of them is equivalent to adding…

    • Note: Object.assign does not return a new Object. Instead, assign returns the heap memory address of obj1.

    let obj1 = {
        x: 100.y: 200
    }
    
    let obj2 = {
        y: 300.z: 400
    }
    let obj = Object.assign(obj1, obj2)
    console.log(obj === obj1) // true Here is the solution
    console.log(Object.assign({}, obj1, obj2))
    Copy the code
  • Object.assign is a shallow comparison.

    • Obj2. n overwrites obj1.n
    let obj1 = {
        x: 100.y: 200.n: {
            0: 1.1: 2}}let obj2 = {
        y: 300.z: 400.n: {
            name: 'zhufeng'}}Copy the code

2.

  • The difference between the two

    • The fn1() {} function is “not a constructor” without the prototype attribute

    • Fn2: function() {} is the same as a normal function

let obj = {
    fn1() {},
    fn2: function() {}}Copy the code