javascript foundation consolidation


// The eval method executes executed js script code
<script id="a">

Prototype Chain

// instanceof detects whether the prototype on the right exists on the u proto_u prototype chain on the left
 1. A construct or without a prototype points to itself

commonjs es6

  • 1 The output is a copy of the value, that is, the change of the value in the original module will not affect the static analysis of the loaded value 2, the dynamic reference, the output is the reference of the value, the value changes, the reference also changes
  • 1 this points to the current module 2 this points to undefined

es6 note

// 1. let is not precompiled, no variable promotion exists
// 2. Variables cannot be defined repeatedly
// 3 Arrow function without arguments
// 4 Arrow functions cannot be constructors
let file_name = "huahua.png"
//  Include string
//  Who started string 
//  Ending 
function test(){
  // arguments is a class array object not an array 
  let arg = arguments;
  // let res = Array.prototype.slice.apply(arg)
  //  1. Turn class arrays into arrays 2. Turn strings into arrays 
  let res = Array.from(arg)


 var person = {
        name: "tom",
        age: 23
    var handler = {
        get: function(target, key, receiver){
            console.log(this) // handler
            return target["name"];
        set: function(target, key, value , receiver){
            target[key] = value
            return true;

         * @name  in Operating hook
        has: function(target, prop){
            return true;
        // When reading the prototype of a proxy object
        getPrototypeOf(target) {

         * @name Object.defineProperty() operation used to intercept objects
         * @param target
         * @param property
         * @param descriptor
         * @returns {boolean}
         * @eg
         * Object.defineProperty(proxy, "sex", {
         *       value:"male",
         *       writable:true,      // Can be overridden
         *       enumerable: true    //Can be traversed
         *   })
        defineProperty(target, property, descriptor){
            console.log(target, property, descriptor)
            // A Boolean value must be returned or an error will be reported
            return true;

         * @name  Intercept delete property actions on objects
         * @param target
         * @param property
         * @returns {boolean}
         * @eg delete;
        deleteProperty(target, property){
            return true;
    var proxy = new Proxy(person,handler);

    console.log(name in proxy)

Deep understanding of bind

There is a case where this points to 
1 Function Nested Function
2 closure
3 Constructor
bind Just return a function, not execute 
1. Event handling, callback functions are best handled separately for ease of maintenance
2. A constructor is a normal function if it is not executed, otherwise it generates this pointing to an instance
3. The constructor bind, which instantiates the object, is not bind's this
function Dog(){
let context = {
   name: 'context1', food: "banana"
let Dog1 = Dog.bind(context);
let dog1 = new Dog1()

console.log(Function.prototype.bind().name)// bound
Function.prototype.binding = function () {
            const _this = this;
            const [context, ...args] = Array.from(arguments)
            // Grail Mode Solves prototyoe Problem
            const tempFn = function () {}
            const bound = function (args1) {
                // if no args the args1 is undefined will throw error 
                args1 = args1 || [];
                args1 = Array.from(args1);

                // Here return is the return in the simulation function
                return _this.apply(this instanceof _this ? this : context, [...args, ...args1])
            tempFn.prototype = _this.prototype;
            bound.prototype = new tempFn();
            return bound;

proxy pattern

 var data = { id: 'hua', val: ''}
      function bindDomToData(data){
        const dom = document.getElementById(;
        function handleChange(){
          data.val = this.value;
        dom.addEventListener("input", handleChange)

      const handler = {}
      handler.set = function (target, key, value, receiver) {
          document.getElementById( = value;
          return Reflect.set(target, key, value, receiver);
      handler.get = function (target, key, receiver) {
         return target[key]
      var proxy = new Proxy(data,handler);

      document.getElementById("click").onclick = function(){
        proxy.val =  Math.random().toFixed(6)


There is a global object with special methods directly mounted on it that can be used as Reflect.apply, all of which can be found in the prototype chain of the Object.

Functional programming

javascript is a mixture of functional programming and object-oriented programming, which is extensible.
Functional programming falls into the category of life programming.
Functional programming is characterized by the fact that the parameters of a function can be functions or return values can be functions.
The higher-order functions are as follows

var  shout = function(out){
  var random = (Math.random() * 321).toFixed(3);
  return function(message){
    out(`#${random} ${message.toUpperCase()}!!!`)
var out = function(mes){
var tell = shout(out)
tell("I am a cool boy")

function compute(obj){
 return {
   add: function(){
       return obj.a + obj.b;
   minus: function(){
       return obj.a - obj.b;
   multiply: function(){
      return obj.a * obj.b;

var data = compute({a : 10 , b : 2})

1 Handwritten instanceof

function _instanceof(A, B) {
    var O = B.prototype; //Pick B display prototype
    A = A. u proto_;//Implicit prototype of A
    while (true) {
        //Object.prototype.__proto__ === null
        if (A === null)
            return false;
        If (O == A)//Here's the main point: Returns true when O is exactly equal to A
            return true;
        A = A.__proto__;

2 deep copies

   function deepClone(data) {
        if(typeof data === "object" && data !== null){
            var type = data.constructor;
            var result = new type();
            for (var key in data) {
                if (data.hasOwnProperty(key)) {
                    result[key] = deepClone(data[key]);
            return result;
        return data;

3 Array Dimension Reduction

var arr = [1, 2, [3]];
var res = Array.prototype.concat.apply([], arr);
var arr2 = [1];

// es6 
let flatten = arr => arr.reduce((begin,current)=>{
        return begin

4 tofixed returns string

let aa = 10937843.44;
console.log(typeof aa.toFixed(3));

5 Function declarations and function expressions

let test = function aa(){} //  This is an expression that ignores names 
let test1 = function(){}
console.log( // aa 
console.log( //test1 

6 Function Parameters and Actual Parameters

function tmp(a,b){
  console.log(tmp.length) // 2 denotes the number of function parameters 
function sum(a,b,c){
  a = 11;
  console.log(arguments[0]) // Mapping relationship between formal and actual parameters (both exist before mapping)
  c = 2;
  console.log(arguments[2]) // undefined  

7 js Execution Order

// -1 Syntax Analysis
 // - 2 Precompilation occurs just before the function executes 
//Function declaration overall promotion, variable declaration promotion only 
//Precompiled procedure (mainly reading variable declarations)
// 1. Create an AO object (Active Object) 
// 2. Look for function parameters and variable declarations within the function. Parameter names and variable names are attributes of the AO object with a value of undefined 
// 3. Arguments are uniform and their values are assigned to parameters 
// 4. Look for function declarations, function names as attributes of AO objects, values as function references
 Global is GO is window 
function test(){
    var b = 10; //Regardless of if, precompilation handles declarations as it sees them 

// - 3 Interpretation of execution 


// The numbers in js are 64 bits, 0-51 are numbers, 52-63 are exponents, 64 bits are symbolic bits
// Bit operations are performed binary with 32 bits

// toString can be converted 
var a = 10;
a.toString(2) // "1010"


The default is greedy matching, that is, as many matches as possible

// Turn on lazy matching 

var reg = /\d+/g;
var reg1 = /\d+?/g;
var str = '11aa22';
console.log(str.match(reg)) // [ '11', '22' ]
console.log(str.match(reg1))// [ '1', '1', '2', '2' ]

Events, Asynchronous

  • The concept of events
    Events: Refers to specific moments of interaction that occur in a document or browser window.We can schedule events through listeners (or handlers) so that the corresponding code can be executed when the event occurs.
  • Event Flow
  1. Event Flow: Describes the order in which events are accepted on a page
  2. Event Bubble: Received by the most specific element and propagated up to the least specific element node (document)
  3. Event Capture: The least specific node receives events first, and the most specific node should receive events last
  4. Capture then Bubble If we click on a div, we actually click on the document first, then click on the event to pass it to the div, and it doesn't stop at that div, the div has child elements that pass down, and the bubbles that pass back to the document
  5. Compatible triggering of an event on the DOM results in an event object event that exists only during event handler execution and is destroyed once event handler execution is complete
  • event processing
  • HTML event handling: adding directly to the HTML structure
  • DOM0 level event handling: assign a function to an event handler property, and event handlers added in this way are handled during the bubble phase of the event flow
 //For DOM0 events, only one can be registered for the same dom node, and the same events registered after overwrite those previously registered
 var btn5 = document.getElementById('btn5');
  • 3.DOM2 level event handling:
    AddEventListener (Event Name, Event Handler, Boolean)
    false means that the event handler is called during the event bubble phase. It is generally recommended to use it during the bubble phase, but only in capture phase in special cases.
    true:Event Capture
    false: Event Bubble


  • Prototype Chain Inheritance
   * @title Prototype Chain Inheritance
   * @good Simple and easy to implement
   * @good An instance is an instance of a subclass and is actually an instance of a parent class
   * @good Parent class adds prototype methods/properties, accessible to all subclasses
   * @bad The prototypes of all instances of subclasses share the properties and methods of the same superclass instance
   * @bad Multiple Inheritance Not Implementable
  function A() { = 'A'

  A.prototype.list = []

  const a = new A()
  function B() { = 'B'

  B.prototype = new A();

  const b = new B();


  • Constructive Inheritance
   * @title Constructive Inheritance
   * @good Resolved parent attribute, subclass sharing problem
   * @good Can inherit more, call more
   * @good Parameters can be passed to the parent class
   * @bad Attributes and methods on the prototype chain cannot be inherited
   * @bad Instances are not instances of the parent class, but instances of the subclass cat instance of Animal are false
   * @bad Function reuse is not possible, each subclass has a copy of the parent instance function, which affects performance
  function C() {
    this.say = ';llllll'

  const c = new C()


  • Classic Inheritance
function create(obj) {
    if(Object.create) {
    return Object.create(obj);  
    } else {
    function F(){};
    F.prototype = obj;
    return new F();
Four original articles have been published. 0% praised. 7% visited
Private letter follow

Keywords: Programming Javascript Attribute

Added by stb74 on Sat, 18 Jan 2020 06:08:04 +0200