web development, online training, jquery display and hide animation

javascript article

1, Data type

There are several types of JavaScript

  • Basic data types: undefined, null, boolean, number, string, symbol (new data type of ES6)
  • Reference data types: object, array, function (collectively referred to as object)

Data type detection

typeof , for basic data types, the correct type can be displayed except , null , and for objects, objec will be displayed except for functions

typeof 5 // 'number'
typeof '5' // 'string'
typeof undefined // 'undefined'
typeof false// 'boolean'
typeof Symbol() // 'symbol'
console.log(typeof null)  //object
console.log(typeof NaN)   //number

typeof [] // 'object'
typeof {} // 'object'
typeof console.log // 'function'

instanceof judges the data type through the prototype chain

p1 = new Person()
p1 instanceof Person // true

Object.prototype.toString.call() can detect all data types, which is a perfect method.

var obj={}
var arr=[]
console.log(Object.prototype.toString.call(obj))    //[object Object]
console.log(Object.prototype.toString.call(arr))    //[object Array]

Deep and shallow copy

Shallow copy

Object.assign()    //es6 method

Object.assign merges objects to produce a new object. If the attribute of an object is a common type, the new object will not change after the change. If the reference type changes, the new object will also change, so object Assign is actually a shallow copy.

var obj={aa:1,b:{item:'45'}};
var newObj=Object.assign({},obj);
obj.aa=2;
obj.b.item='kk';
console.log(newObj.aa);        //1
console.log(newObj.b.item);    //kk

Deep copy

JSON.parse(JSON.stringify(obj))

Using json Stringify (obj) converts an object into a json string first, and then json Parse () can be converted back to json object to realize deep copy, which is also a common method.

Implementing a deep copy with js

In fact, deep copy can be divided into two steps, shallow copy + recursion. During shallow copy, judge whether the attribute value is an object. If it is an object, perform recursive operation. The combination of the two realizes deep copy.

  function cloneDeep(source) {
      if (!isObject(source)) return source; // Non object returns itself
      var target = Array.isArray(source) ? [] : {};
      for (var key in source) {
        if (source.hasOwnProperty(i)) {
          if (isObject(source[key])) {
            target[key] = cloneDeep(source[key]); // Pay attention here
          } else {
            target[key] = source[key];
          }
        }
      }
      return target;
    }
    function isObject(obj) {
      return typeof obj === 'object' && obj != null;
    }

2, Scope

Variable declaration promotion

  • In JavaScript, function declaration (function aa() {}) and variable declaration (var) are often implicitly promoted to the top of the current scope by the JavaScript engine.
  • The function declaration takes precedence over the variable. If the variable name is the same as the function name and is not assigned, the function declaration will override the variable declaration
  • The assignment part of the declaration statement is not promoted, only the name of the variable is promoted

Scope chain

Because the nesting of functions forms the hierarchical relationship of scope. When the function is executed, the search starts from the current scope. The variables that are not found will be searched from the upper scope to the global function, which is the scope chain.

  • In JavaScript, the scope is the area within function() {}, which is called the function scope.
  • The global function cannot view the internal details of the local function, but the local function can view the function details of its upper layer until the global details

closure

The principle of closure is the scope chain. There is a function G inside function F. function G can access the variables in function f, so function G is a closure.

   function F() {
      let a = 1
      window.G = function () {
        console.log(a)
      }
    }
    F()
    G() // 1

3, Prototype and inheritance

Several ways of creating objects in js

Object literal

var obj={};

new is a constructor

function Pel(){}
    var p=new Pel();
    p.name="hu";
    p.age="25";
    p.address=function(){
 }

new a built-in pair

var obj=new Object();

Object.create() creates an object

var test = Object.create({x:1});

Let's leave a question for you, new Object(), object Create (), {}. What is the difference between the three methods of creating objects.

How does JS implement a class

Constructor method

Disadvantages: this and prototype are used, the writing is complex and the readability is poor

function P(name, age){
     this.name = name;
     this.age= age;
   }
   P.prototype.sal= function(){

   }
   var pel= new P("jj", 1);
   pel.sell()

ES6 syntax class

class Point {
       constructor(x, y) {
         this.x = x;
         this.y = y;
       }
       toString() {
         return '(' + this.x + ', ' + this.y + ')';
       }
     }
  var point = new Point(2, 3);

Prototype chain

What is a prototype chain in one sentence

When traversing the properties of a real column, first traverse the properties on the real column Object, and then traverse its prototype Object until it reaches Object

Any class (function) has a prototype object, which has at least two properties (constructor,proto). Constructor points to the function itself and proto points to the parent prototype object.

There is a prototype attribute on the function, which points to the prototype object, through which you can access the prototype object

The real column of the function can directly access the prototype object (because there is a prototype object on the real column that proto points to the constructor)

function Dog(){}        //class         
var obj=new Dog();      //Real column
obj.name='another name for Shanghai';
Dog.prototype.name="Wangcai";
Dog.prototype.eat=function(){
    console.log(this.name);
};
console.log(Dog.prototype.name);  //Wangcai
console.log(obj.prototype);      //Undefined and prototype are only available on the class, but not on the real column
obj.eat();                       //Hujiang (first traverse the properties on the real column object, and then traverse its prototype object)

inherit

How does Js implement inheritance?

Constructor binding: use the call or apply method to bind the constructor of the parent object to the child object

function Cat(name,color){
  Animal.apply(this, arguments);
  this.name = name;
  this.color = color;
}

Instance inheritance: point the prototype of the child object to an instance of the parent object

Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;

Copy inheritance: if all the properties and methods of the parent object are copied into the child object

function extend(Child, Parent) {
   var p = Parent.prototype;
   var c = Child.prototype;
   for (var i in p) {
      c[i] = p[i];
   }
   c.uber = p;
}

Prototype inheritance: point the prototype of the child object to the prototype of the parent object

function extend(Child, Parent) {
    var F = function(){};
     F.prototype = Parent.prototype;
     Child.prototype = new F();
     Child.prototype.constructor = Child;
     Child.uber = Parent.prototype;
}

ES6 syntax extensions inheritance

class ColorPoint extends Point {
    constructor(x, y, color) {
        super(x, y); // Call the constructor(x, y) of the parent class
        this.color = color;
    }
    toString() {
        return this.color + ' ' + super.toString(); // Call the toString() of the parent class
    }
}

❤️ Limited space, more detailed content Click me Get full pdf view ❤️

4, new and this

What exactly does the new operator do?

What does the new operator do when we new a data?

  • The first is to create the instance object {}
  • The this variable references the object and also inherits the prototype of the constructor
  • Secondly, attributes and methods are added to the object referenced by this
  • And the newly created object is referenced by this, and finally implicitly returns this

Simulation Implementation of new

function objectFactory() {

    var obj = new Object(),//From object Clone an object on Prototype

    Constructor = [].shift.call(arguments);//Gets the constructor passed in externally

    var F=function(){};
    F.prototype= Constructor.prototype;
    obj=new F();//Point to the correct prototype

    var ret = Constructor.apply(obj, arguments);//Borrow the constructor passed in from outside to set properties for obj

    return typeof ret === 'object' ? ret : obj;//Make sure the constructor always returns an object

};

Understanding of this object

Ordinary function

  • this always points to the direct caller of the function
  • If there is a new keyword, this points to the instance object from new
  • In an event, this points to the object that triggered the event
  • this in attachEvent under IE always points to the global object Window
  • In the arrow function, the this object in the function body is the object in the scope when it is defined, not the object in the scope when it is used.
function foo() {
  console.log(this.a)
}
var a = 1
foo()           //1       

const obj = {
  a: 2,
  foo: foo
}
obj.foo()      //2

const c = new foo()   //undefined

  • For calling foo directly, no matter where the foo function is placed, this must be window
  • For obj For foo (), we only need to remember that whoever calls the function is this, so in this scenario, this in the foo function is the obj object
  • For the new method, this is always bound to the new object and will not be changed in any way

After the above situations, in fact, there should be no problem with this in many codes. Let's take a look at this in the arrow function

function a() {
  return () => {
    return () => {
      console.log(this)
    }
  }
}
a()()()        //Window

  • First of all, the arrow function actually does not have this. This in the arrow function only depends on this of the first ordinary function wrapping the arrow function. In this case, the first arrow in the window a function is the normal one. In addition, it is invalid to use bind for arrow functions.

5, apply, call, bind

call, apply, and bind are the three methods of the Function object. They are all used to change the direction of {this} in the Function body.
The first parameter of apply, call and bind , is the object to which , this , refers, that is, the context you want to specify;
apply, call, and bind} can all use subsequent parameters to pass parameters;
bind returns the corresponding function, which is convenient for calling later. apply and call are called immediately.

function fruits() {}

fruits.prototype = {
	color: 'red',
	say: function() {
		console.log(this.color);
	}
};

var apple = new fruits();

apple.say();   // red, this in the method refers to fruits

banana = {color: 'yellow'};
apple.say.call(banana); //Yellow, the point of this has been changed through the call () method, pointing to banana, this Color is banana color='yellow';

apple.say.apply(banana);//Yellow, similarly, the direction of this has been changed through the apply () method, pointing to banana, this Color is banana color ='yellow';

apple.say.apply(null); //Under window.defined, the window.defined attribute is null, but it does not point to this clolr is window color=undefined;

call incoming parameter list
apply pass in array

var array1 = [12,'foo'];
var array2 = ['Doe',100];

Array.prototype.push.call(array1, 'Doe',100)
Array.prototype.push.apply(array1, array2)

The bind() method will create a new function. When calling this new function, the new function will call the original function with the first parameter passed in the bind() method as this, the second and subsequent parameters passed in the bind() method plus the parameters of the binding function itself when running in order as the parameters of the original function.

var bar = function(){
	console.log(this.x);
};
var foo = {
	x:3
};
bar();    // undefined
var func = bar.bind(foo); 

func(); // 3

6, Data processing

Array de duplication

var arr=['12','32','89','12','12','78','12','32'];
    // The simplest array de duplication method
    function unique1(array){
        var n = []; //A new temporary array
        for(var i = 0; i < array.length; i++){ //Traverse the current array
            if (n.indexOf(array[i]) == -1)
                n.push(array[i]);
        }
        return n;
    }
    arr=unique1(arr);

sort

/**
	 * Sort by sort and id
	 * @param {Object} a
	 * @param {Object} b
	 */
 function   sortFun(a, b) {
       return a.sort - b.sort == 0 ? a.id - b.id : a.sort - b.sort
  };
 arr.sort(sortFun)   //Sort from small to large

Recursive summation

    function add(num1,num2){
	var num = num1+num2;
		if(num2+1>100){
		   return num;
	         }else{
	            return add(num,num2+1)
	        }		   	
     }
     var sum =add(1,2)

Count the number of repetitions of array items

var arr=['Hu Jiang','Hu Jiang','hujiang','Hu Jiang','Hu Jiang','hujiang'];
var obj={};
arr.sort();    //Sort first
for(var i=0;i<arr.length;){
	var con=0;
	for(var j=i;j<arr.length;j++){
		if(arr[i]===arr[j]){
			con++
		}
	}
	obj[arr[i]]=con; 
	i=i+con;    //Skip duplicate values
}
console.log(obj);  //{hujiang: 2, 'Hu Jiang': 3, 'Hu Jiang': 1}

7, Event Loop

Macro task / micro task

In addition to the generalized synchronous tasks and asynchronous tasks, we have a more detailed definition of tasks:

  1. Macro-task (macro task): the task currently executed in the call stack is called macro task. Including: all script codes, setTimeout, setInterval and setImmediate (the browser does not support it temporarily, only IE10 supports it. For details, see MDN),I/O,UI Rendering.
  2. . micro task: the current macro task (in this event cycle) is completed, and the task to be executed before the next macro task starts is a micro task. Including: process Nexttick (unique to Node), Promise, object Observe, MutationObserver
  3. Different types of tasks will enter the corresponding Event Queue. The events in the macro task will be placed in the callback queue, which will be triggered by the event and maintained by the thread; The micro task events are placed in the micro task queue and maintained by the js engine thread.

What is event loop in one sentence

  • When the main thread runs, it will generate heap and stack;
  • js parses the method from top to bottom, and arranges the synchronization tasks in the execution stack according to the execution order;
  • When the program calls an external API (such as ajax, setTimeout, etc.), it will suspend such asynchronous tasks and continue to execute the tasks in the stack. After the asynchronous task returns the results, it is arranged in the event queue in order;
  • The main thread first empties the synchronous tasks in the execution stack, and then checks whether there are tasks in the event queue. If so, it pushes the callback corresponding to the first event to the execution stack for execution. If an asynchronous task is encountered during execution, it continues to arrange the asynchronous task into the event queue.
  • Each time the main thread empties the execution stack, it goes to the event queue to check whether there are tasks. If there are, it takes out one at a time and pushes it to the execution stack for execution. This circular process is called "Event Loop event loop"

❤️ Limited space, more detailed content Click me Get full pdf view ❤️

8, Browser page rendering pass

The general process of rendering a page by browser:

1. The browser parses the HTML source code, and then creates a DOM tree. Parallel request css/image/js in the DOM tree, each HTML tag has a corresponding node, and each text will also have a corresponding text node. The root node of the DOM tree is the documentElement, which corresponds to the HTML tag.

2. The browser parses the CSS code and calculates the final style data. Build CSSOM tree. It will directly ignore illegal syntax in CSS code. When parsing CSS, the priority will be defined in the following order: browser defau lt setting < user setting < outer chain style < inline style < style in HTML.

3. DOM tree + cssom -- > rendering tree. A render tree is a bit like a DOM tree, but there are differences.

The DOM tree completely corresponds to the html tag one by one, but the rendering tree ignores elements that do not need to be rendered, such as the elements of head and display:none. Moreover, each line in a large piece of text is an independent node in the rendering tree. Each node in the rendering tree stores a corresponding css attribute.

4. Once the rendering tree is created, the browser can draw the page directly to the screen according to the rendering tree.

The above four steps are not completed in sequence at one time. If DOM or CSSOM is modified, the above process will be repeated. In fact, CSS and JavaScript often modify DOM or CSSOM many times.

9, Browser cache

This content is often asked in the interview about strong caching and negotiation caching. More detailed content Click me Get full pdf view

css

1, Box model

The box model consists of content, padding, border and margin from inside to outside

In the IE box model, width represents the width of content+padding+border

In the standard box model, width refers to the width of the content part

Use of box sizing

box-sizing: content-box yes W3C Box model
  box-sizing: border-box yes IE Box model

The default attribute of box sizing is content box

2, Center

horizontally

  • Inline element: text align: Center
  • Block level element: margin: 0 auto
  • position:absolute +left:50%+ transform:translateX(-50%)
  • display:flex + justify-content: center

Vertical center

  • Set line height equal to height
  • position: absolute +top:50%+ transform:translateY(-50%)
  • display:flex + align-items: center
  • display:table+display:table-cell + vertical-align: middle;

//I don't know the width and height

  width: 78px;
  height: 78px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);

//Know width and height

        height: 100px;
        width: 100px;
        position: absolute;
        left:50%;
        top: 50%;
        margin-left: -50px;
        margin-top: -50px;
        display:flex;
        justify-content: center;
        align-content: center;

Later words

For the interview, say a few personal views.

Interview, in the final analysis, is a kind of examination. Just as we have always criticized that exam oriented education is divorced from the essence of education, learning technology for interview is also divorced from the original intention of technology. However, there is no doubt about the effectiveness of examination in talent selection, which has been the case for thousands of years. Unless you have the strength to prove to the company that you are good enough, you still have to prepare for the interview. This does not prevent you from learning your own way after passing the interview.

In fact, in the interview preparation stage, personal gains are great. I also think this is a good way to learn. First of all, most of the interview questions are basic and in-depth, which are the basis of daily work. It's like we didn't understand the meaning of learning Chinese before, but its meaning lies in our daily conversation.

The so-called interview makes a rocket, work screws. Interviews often have higher requirements, but also force us to concentrate more deeply on learning some knowledge, which is not a good thing.

Keywords: Front-end Interview Programmer

Added by brighton on Sat, 15 Jan 2022 00:54:52 +0200