Shenzhen everyone gathers money to recruit front end ~~~

Recruit front end, recruit front end, recruit front end, welcome to scan code add group, hit resume:

preface

This period of time suddenly found that JS native a lot of things have forgotten, but some things are really important, so again comb again. There are three main definition methods of function, ES5 function this pointing, call and appL usage, 4 common design patterns of JS, prototype chain, prototype chain and inheritance (ES5 and ES6).

1. Three definitions of functions

1.1 Function Declaration

/ / ES5 function getSum {} () function () {} / / / / ES6 anonymous methods () = > {} / / if the single lines of {} {} content can be saved and the return keyword,Copy the code

1.2 Function Expressions (Function literals)

/ / ES5 var sum = function () {} / / ES6 let sum () = = > {} / / if the single lines of {} {} content can be saved and the return keyword,Copy the code

1.3 Constructors

var sum=new GetSum(num1,num2)
Copy the code

1.4 Comparison of the three methods

1. Function declarations are pre-parsed, and function declarations take precedence over variables; 2. Using the Function constructor to define a Function as a Function expression causes code to be parsed twice, which affects performance. The first parses regular JavaScript code, and the second parses the string passed in to the constructor

2. Four kinds of function calls in ES5

In ES5, the “this” of a function’s content refers to the calling method

2.1 Function Call Mode

Includes the function name () and the anonymous function call, with this pointing to the window

 function getSum() {
    console.log(this) //window
 }
 getSum()
 
 (function() {
    console.log(this) //window
 })()
 
 var getSum=function() {
    console.log(this) //window
 }
 getSum()
Copy the code

2.2 Method Invocation

Object. Method name (),this refers to the object

Var objList = {name: 'methods', getSum: function() {console.log(this)}} objlist.getsum ()Copy the code

2.3 Constructor calls

New constructor name (),this points to the constructor

function Person() { console.log(this); Person} var personOne = new Person();Copy the code

2.4 Indirect Invocation

Call and apply are used to implement this. This is the first parameter corresponding to call and apply. If no value is passed or the first value is null,undefined this points to window

function foo() { console.log(this); } foo.apply(' I am this value changed by apply '); Call (' I am this value changed by call '); // I change this value by callCopy the code

3. Function calls in ES6

Arrow functions cannot be used as constructors, that is, they cannot instantiate an object with the new command, otherwise an error will be thrown

(() => {
   console.log(this)//window
})()

let arrowFun = () => {
  console.log(this)//window
}
arrowFun()

let arrowObj = {
  arrFun: function() {
   (() => {
     console.log(this)//arrowObj
   })()
   }
 }
 arrowObj.arrFun();
Copy the code

4. Call the apply and bind

1. Before IE5, call and apply were not supported. Bind came from ES5. 2. Call and apply can call functions, change this, and implement methods that inherit or borrow from other objects.

4.1 Call and Apply definitions

Call (new this object, argument 1, argument 2, argument 3…..) Apply (new this object,[argument 1, argument 2, argument 3…..] )

4.2 Usage of Call and apply

1. Call a function indirectly, changing the value of this in the scope. 2

Var foo = {name:" foo ", logName:function(){console.log(this.name); }} var bar={name:" "}; foo.logName.call(bar); // Call changes foo's this pointer to bar and calls that functionCopy the code

3. The two functions implement inheritance

function Animal(name){   
  this.name = name;   
  this.showName = function(){   
    console.log(this.name);   
  }   
}   
function Cat(name){  
  Animal.call(this, name);  
}    
var cat = new Cat("Black Cat");   
cat.showName(); //Black Cat
Copy the code

4. Add array methods push,pop for class arrays (arguments and nodeList)

(function () {Array. Prototype. Push. The call (the arguments, 'Cathy'); console.log(arguments); //[' zhang SAN ',' Li Si ',' Wang Si ']})Copy the code

5. Merge arrays

Let arr1 = [1, 2, 3]; Let arr2 = (4 and 6); Array.prototype.push.apply(arr1,arr2); // merge arR2 into ARR1Copy the code

6. Find the maximum array size

Math.max.apply(null,arr)
Copy the code

7. Determine the character type

Object.prototype.toString.call({})
Copy the code

4.3 the bind

Bind is a function extension of function. Bind rebinds this in func and does not call the method, which is incompatible with IE8

Var name = 'foo' var foo = {name: foo, logName: function(age) {console.log(this.name, age); } } var fooNew = foo.logName; var fooNewBind = foo.logName.bind(foo); FooNew (10)// Li Si,10 fooNewBind(11)// Zhang SAN,11 because bind changed the this pointer in fooNewBindCopy the code

5. Four common design patterns of JS

5.1 Factory Mode

The simple factory pattern can be understood as solving multiple similar problems;

function CreatePerson(name,age,sex) { var obj = new Object(); obj.name = name; obj.age = age; obj.sex = sex; obj.sayName = function(){ return this.name; } return obj; } var p1 = new CreatePerson("longen",'28',' male '); Var p2 = new CreatePerson("tugenhua",'27',' female '); console.log(p1.name); // longen console.log(p1.age); // 28 console.log(p1.sex); / / male console. The log (p1. SayName ()); // longen console.log(p2.name); // tugenhua console.log(p2.age); // 27 console.log(p2.sex); / / female console. The log (p2. SayName ()); // tugenhuaCopy the code

5.2 Singleton Mode

Can only be instantiated (constructors add attributes and methods to instances) once

Var Singleton = function(name){this.name = name; }; Singleton.prototype.getName = function(){ return this.name; Var getInstance = (function() {var instance = null; return function(name) { if(! Instance = new Singleton(name); instance = new Singleton(name); } return instance; }}) (); Var a= getInstance("aa"); var b = getInstance("bb");Copy the code

5.3 Sandbox Mode

Put some functions inside self-executing functions, but expose the interface with a closure, receive the exposed interface with a variable, and then call the value inside, otherwise you can’t use the value inside

let sandboxModel=(function(){
    function sayName(){};
    function sayAge(){};
    return{
        sayName:sayName,
        sayAge:sayAge
    }
})()
Copy the code

5.4 Publisher Subscription Mode

For example, if we follow a certain public account, then the corresponding new news will be pushed to you,

Var shoeObj = {}; Shoeobj.list = []; Shoeobj. listen = function(fn) {shoeobj.list.push (fn); Shoeobj.trigger = function() {for (var I = 0, fn; fn = this.list[i++];) { fn.apply(this, arguments); ShoeObj. Listen (function(color, size) {console.log(" color is: "+ color); Console. log(" size: "+ size); }); Shoeobj. listen(function(color, size) {console.log(" print again color is: "+ color); Console. log(" Print again size is: "+ size); }); Shoeobj.trigger (" red ", 40); Shoeobj.trigger (" black ", 42);Copy the code

The implementation logic of the code is to store subscribers in an array, and the notification in the publisher callback function is to traverse the subscriber array and pass the publisher content into the subscriber array

Common design patterns in Javascript

6. The prototype chain

6.1 define

Object inherits a chain of properties

6.2 Constructors, relationship between instance and prototype object

Picture description

var Person = function (name) { this.name = name; } person is the constructor var o3personTwo = new person ('personTwo')//personTwo is the instanceCopy the code

Picture description

Stereotype objects have a default constructor property pointing to the constructor

6.3 Method for Creating an Instance

1. Literal

Let obj={'name':' zhang SAN '}Copy the code

2. Create the Object constructor

Let Obj=new Object() Obj.Copy the code

3. Use factory mode to create objects

function createPerson(name){ var o = new Object(); o.name = name; }; return o; } var person1 = createPerson;Copy the code

4. Use constructors to create objects

function Person(name){ this.name = name; } var person1 = new Person(' person1 ');Copy the code

6.4 New operator

1. Create a new object; 2. This points to the constructor; 3. The constructor returns a return that replaces the new object, or if not, the new object 4. Manually encapsulate a new operator

var new2 = function (func) { var o = Object.create(func.prototype);     Var k = func.call(o);                           If (typeof k === 'object') {  if (typeof k === 'object') {                  Return k;                                   // If yes, return k} else {return o;                                   Return the result of the constructor}}Copy the code

More on JavaScript prototype chains

6.5 Prototype chain of objects

Picture description

7. Inheritance

JS is a weakly typed dynamic language, encapsulation and inheritance are its two major characteristics

7.1 Inheritance of prototype chain

1. The code implementation defines the parent class:

/ / define a Animal function Animal (name) {/ / attribute this. Name = name | | 'Animal'; This.sleep = function(){console.log(this.name + 'sleeping! '); } // animal.prototype. eat = function(food) {console.log(this.name + 'eating:' + food); };Copy the code

The subclass:

function Cat(){ } Cat.prototype = new Animal(); Cat.prototype.name = 'cat'; //  Test Code var cat = new Cat(); console.log(cat.name); //cat console.log(cat.eat('fish')); //cat is eating: fish undefined console.log(cat.sleep()); // Cat is sleeping! undefined console.log(cat instanceof Animal); //true console.log(cat instanceof Cat); //trueCopy the code

2. Advantages and disadvantages are simple and easy to implement, but to add attributes and methods to a subclass, it must be executed after a statement such as new Animal(), which cannot implement multiple inheritance

7.2 Structural Inheritance

Use call to change this in Cat to refer to 1.

function Cat(name){
  Animal.call(this);
  this.name = name || 'Tom';
}
Copy the code

2. Advantages and disadvantages can achieve multiple inheritance, can not inherit the prototype attributes/methods

7.3 Instance Inheritance

Add a new feature to the parent class instance and return it as a subclass instance

function Cat(name){
  var instance = new Animal();
  instance.name = name || 'Tom';
  return instance;
}
Copy the code

2. Advantages and disadvantages Do not limit the invocation method, but can not achieve multiple inheritance

7.4 Copy Inheritance

Copy the attributes and methods of the parent class into the child class.

function Cat(name){
  var animal = new Animal();
  for(var p in animal){
    Cat.prototype[p] = animal[p];
  }
  Cat.prototype.name = name || 'Tom';
}
Copy the code

2. Advantages and disadvantages Multiple inheritance is supported, but it is inefficient and occupies memory

7.5 Combination Inheritance

By calling the superclass constructor, inheriting the attributes of the superclass and retaining the advantages of passing arguments, and then reusing the function 1 by using the superclass instance as a subclass prototype. The subclass:

function Cat(name){
  Animal.call(this);
  this.name = name || 'Tom';
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
Copy the code

7.6 Parasitic combination inheritance

function Cat(name){ Animal.call(this); this.name = name || 'Tom'; } (function(){var Super = function(){}; Super.prototype = Animal.prototype; Cat.prototype = new Super(); }) ();Copy the code

7.7 Extends Inheritance of ES6

The inheritance mechanism for ES6 is to create an instance object of the parent class, this (so the super method must be called first), and then modify this with the constructor of the subclass, linking the description

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

For more details, see :JS inheritance implementation

References:

www.cnblogs.com/tugen…

www.cnblogs.com/humin…

www.cnblogs.com/cheng…

www.cnblogs.com/cheng…