Prototype development method + inheritance

Keywords: Javascript node.js Vue.js

Prototype development method + inheritance

Methods on extended prototypes

Extension of array indexOf

// console.log(Array.prototype.indexOf);
// Return function in standard browser, and return undefined in IE8 and

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (val, index) {
        index = typeof index === 'undefined' ? 0 : index;
        for (var i = index; i < this.length; i++) {
            if (this[i] === val) {
                return i;
            }
        }
        return -1;
    }
}

var arr = [3, 4, 2, 3, 3, 4];
console.log(arr.indexOf(3)); // 0
console.log(arr.indexOf(3, 1)); // 3

Extension of string trim

// String trim

// Return the function in the standard browser, and return undefined in IE8 and below
// console.log(String.prototype.trim);

// Extend trim on IE8 and below prototypes

if (!String.prototype.trim) {
    String.prototype.trim = function () {
        var re = /^\s+|\s+$/g;
        return this.replace(re, '');
    }
}
var str = '    Flat head brother   ';
console.log('(' + str.trim() + ')');

call and apply and bind

  • Function. Call (new this point, parameter 1, parameter 2,...)
  • Function. Apply (new this point, [parameter 1, parameter 2,...])
  • Function. Bind (new this point, parameter 1, parameter 2,...)

Function: both call and apply call the function, but bind will not call the function. Both modify the point of this in the function.

Difference: the subsequent parameters of call and bind are passed in as a parameter list, while the subsequent parameters of apply are passed in as an array

Common points: modify this in the function. The first parameter is a new this point and has a return value. The return values of call and apply are the return values of the function, while the return value of bind is a copy of the original function modified by the specified this value and initialization parameters, because bind will not call the function.

function fn(a, b) {
    console.log(this);
    console.log(a, b);
}

fn(3, 5);
fn.call(document, 5, 6);
fn.apply(document, [7, 8]);

var f = fn.bind(document,5,6);
f();

// --------------------------------
// If the first parameter is null and undefined, this points to window
fn.call(undefined, 5, 6);
// Find the maximum value of the array
var arr = [4, 6, 2, 6, 5, 8, 4, 7, 3];
// Math.max(4, 6, 2, 6, 5, 8, 4, 7, 3)
console.log(Math.max.apply(Math, arr));

inherit

Prototype chain inheritance

  • Prototype chain inheritance: assign the parent instance to the child prototype

  • How to implement inheritance in one sentence: assign the parent instance to the child prototype.

  • Insufficient:

    1. If there is a reference type in the parent, the created child will be completely changed

    2. The constructor should have pointed to its own constructor, but it pointed to the constructor of the parent

// Parent class (student class)
function Student() {
    this.job = 'student';
    this.ah = ['Play games', 'sleep', 'Find a flat head sister'];
}
Student.prototype.showJob = function () {
    console.log(this.job);
}

// ----------------------------------------
// Subclass (primary school students)
function SmallStudent(name) {
    this.name = name; // The child was added by itself
}
SmallStudent.prototype = new Student(); // Inherits the properties and methods of the parent

// Prototype chain inheritance: assign the parent instance to the child prototype
// How to realize inheritance in one sentence: prototype chain inheritance
// Insufficient:
// 1. If there is a reference type in the parent, the created child will change all attributes
// 2. The constructor should have pointed to its own constructor, but it pointed to the constructor of the parent
//Solve the problem 1. Manually change the direction of the constructor
SmallStrudent.prototype.construcor = SmallStrudent;


// -------------------------------------
var s1 = new SmallStudent('zs');
console.log(s1);
console.log(s1.name);
console.log(s1.job);
console.log(s1.ah);
s1.showJob();
console.log(s1.constructor); // Student, which should have pointed to SmallStudent

s1.ah.push('draw'); // Modify s1's hobby, and the s2 created later will also change

var s2 = new SmallStudent('ls');
console.log(s2);
console.log(s2.ah); // ["play games", "sleep", "find a flat head sister", "draw"]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-MeC69Qsr-1632922046835)(C:\Users\Administrator\Desktop \ class notes \ phase II \ notes \ image \ prototype chain inheritance. jpg)]

Object impersonation (call) inheritance

  • Object impersonation inheritance: in the child constructor, call the constructor of the parent class, and use call to change the this direction.
  • Insufficient: cannot inherit method on prototype.
// Parent class (student class)
function Student() {
    this.job = 'student';
    this.ah = ['Play games', 'sleep', 'Find a flat head sister'];
}
Student.prototype.showJob = function () {
    console.log(this.job);
}

// ----------------------------------------
// Subclass (primary school students)
function SmallStudent(name) {
    Student.call(this); // Inherits the properties in the parent class constructor
    this.name = name; // Add my own attributes
}

// The object is assumed to be inherited: in the constructor of the subclass, the constructor of the parent class is constructed, and call is used to change the this direction.
// Benefits: it solves the problem that the prototype chain inherits the reference type and changes all attributes
// Problem: it only inherits the properties of the parent class, but does not inherit the methods on the parent class prototype

// -----------------------------------
var s1 = new SmallStudent('zs');
s1.ah.push('draw');
console.log(s1);


var s2 = new SmallStudent('ls');
console.log(s2);

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG vagcjnvc-1632922046839) (C: \ users \ administrator \ desktop \ class notes \ phase II \ notes \ image \ object impersonation inheritance. jpg)]

Composite inheritance (implemented but wasted performance)

  • Composite inheritance: object impersonation + prototype chain
  • Object impersonates an inherited property
  • Prototype chain inheritance method
// Parent class (student class)
function Student() {
    this.job = 'student';
    this.ah = ['Play games', 'sleep', 'Find a flat head sister'];
}
Student.prototype.showJob = function () {
    console.log(this.job);
}

// ----------------------------------------
// Subclass (primary school students)
function SmallStudent(name) {
    Student.call(this); // Object impersonation inheritance
    this.name = name;
}
SmallStudent.prototype = new Student(); // Prototype chain inheritance


// Composite inheritance: prototype chain inheritance + object impersonation inheritance
// problem
// 1. The constructor is not pointing correctly
// 2. An attribute with the same name appears twice in the prototype chain
// 3. The parent constructor is called twice


//Solve the problem 1. Manually change the direction of the constructor
SmallStrudent.prototype.construcor = SmallStrudent;

// -------------------------------------------
var s1 = new SmallStudent('zs');
console.log(s1);

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-rLLhy4Ty-1632922046842)(C:\Users\Administrator\Desktop \ class notes \ phase II \ notes \ image \ combined inheritance. jpg)]

Prototype chain inheritance diagram:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-4SiwsEZt-1632922046845)(C:\Users\Administrator\Desktop \ class notes \ phase II \ notes \ image \ Sogou screenshot 20210910095431.png)]

Parasitic composite inheritance (standard mode of inheritance)

// Parent class (student class)
function Student() {
    this.job = 'student';
    this.ah = ['Play games', 'sleep', 'Find a flat head sister'];
}
Student.prototype.showJob = function () {
    console.log(this.job);
}

// ----------------------------------------
// Subclass (primary school students)
function SmallStudent(name) {
    Student.call(this); // Inherit properties from parent
    this.name = name; // Add the subclass's own properties (written after inheritance)
}

// Inherits methods on the parent prototype
inherits(SmallStudent, Student);

// When adding methods on your prototype, be sure to write them after inheritance
SmallStudent.prototype.showName = function () {
    console.log(this.name);
}

// Parasitic combinatorial inheritance (standard pattern of inheritance)
// The properties and methods of the parent should be inherited separately

// -----------------------------------------
var s1 = new SmallStudent('zs');
console.log(s1);
// console.log(s1.constructor);


// ------------------------------------------
// Parasitic composition inherits the encapsulation of methods on the parent class prototype, and the prototype chain inherits and upgrades
function inherits(Child, Parent) {
    var F = function () { };
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
}

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-TqT3xLvi-1632922046848)(C:\Users\Administrator\Desktop \ class notes \ phase II \ notes \ image \ object impersonation inheritance. jpg)]

Prototype chain inheritance upgrade diagram:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Wog0ty7S-1632922046849)(C:\Users\Administrator\Desktop \ class notes \ phase II \ notes \ image \ prototype chain upgrade. png)]

Prototype object reference summary (address problem)

  • The arrow in the above figure points to who, that is, whose address is referenced, such as the Fun instance__ proto__ Point to the Fun prototype, that is, the address where the Fun instance gets the Fun prototype.
  • Son.prototype = new Fun(); Indicates that son.prototype gets the address of the fun instance object. In this case, if the assignment form is adopted, the content of son.prototype will change, and the content in fun will also change, because the address is the same.
  • And Fun instance__ proto__ Point to the Fun prototype. If the Fun instance gets the address of the Fun prototype, changing the Fun instance will not change the Fun prototype because they use__ proto__ Point to. If you change the Fun instance__ proto__ Will change the Fun prototype. Similarly: the prototype is the same as the. constructor.
  • Fun.prototype = Farther.prototype; express

Inheritance application

Judge all data types

var obj = {};
console.log(obj);

//this points to the instance object obj. So print [object].
console.log(obj.toString());

//Originally, call this directly to point to the prototype Object of the Object. So print [Object].
console.log(Object.prototype.toString());

//Change this point of toString. Make this point to the instance object. The instance object is the data type, which is constructed by different constructors. Print [object constructor].
console.log(Object.prototype.toString.call());

//Example: 1 is an instance object of the Number constructor, so print [object Number].
console.log(Object.prototype.toString.call(1));

Precautions for image objects

Reference method of instance object method

function Person() {
    this.uname = 'student';
    this.age = 1;
    this.fn2();//The second way.
}
Person.prototype.fn1 = function () {
    console.log(1);
}
Person.prototype.fn2 = function () {
    console.log(2);
}
Person.prototype.fn3 = function () {
    console.log(3);
}

var s1 = new Person();
s1.fn1();//The first way.

new.Person().fn3();//The third way.

The direction of this

   this Point to who calls for whom, mainly depends on whose scope. The function with this scope points to whoever is called.
- Who called the function, this To whom
- this It is not determined at the time of definition, but at the time of invocation

// 1. this: window in global environment
         console.log(this);

// 2. This: in the event handler is the element that triggers this event
         box.onclick = function () {
             console.log(this); // box
         }

        
// 3. this: window in timer
         setTimeout(function () {
             console.log(this);
         }, 1000);


// 4. this function is directly executed. The non strict mode is window and the strict mode is undefined
        //"use strict"; //  Strict mode
         function fn() {
             console.log(this);
         }
        fn();

       
 // 5,call apply

// 6. Object method internal call
     var obj = {
      fn: function () {
          console.log(this);
           }
        };
       
      obj.fn(); // obj
        
      var v = obj.fn;
      v(); // window
     
// 7. Which object (instance) comes out of this: new in the constructor
new Assign the scope of the constructor to the new object (so this It points to the new object).
     
// 8. this in the prototype chain function generally refers to an instance
 Because it can only be used by instance calls.   
        
// 9. this in all callback functions is window
        move(box, {}, function () { })
This callback function is an argument in the global scope.

Method internal call
var obj = {
fn: function () {
console.log(this);
}
};

  obj.fn(); // obj
    
  var v = obj.fn;
  v(); // window

//7. Which object (instance) comes from this: new in the constructor
New assigns the scope of the constructor to the new object (so this points to the new object).

//8. this in the prototype chain function generally refers to an instance
Because it can only be used by instance calls.

//9. this in all callback functions is window
move(box, {}, function () { })
This callback function is an argument in the global scope.



Posted by MicahCarrick on Wed, 29 Sep 2021 11:17:36 -0700