Recently the company has been busy with the development of the new version of the function every day overtime… PS: Learn the core principles and applications of JavaScript design patterns from digging gold

A concept,

The core idea of the prototype programming paradigm is to use instances to describe objects and use instances as the basis for defining objects and inheritance. In JavaScript, the prototype programming paradigm is represented by inheritance based on prototype chains.

Second, the prototype

  • 1. The concept

A. In js, each constructor has a prototype property that points to the constructor’s prototype object. The constructor property has a constructor property that points back to the constructor. B. Each instance has a __proto__ attribute. When we create an instance using a constructor, the __proto__ attribute of the instance points to the protoobject of the constructor.

  • 2. Code cases
// the constructor function Person(name, Prototype. Chat = function (){console.log(' human communicate through language ')} // instantiate object Const xiaoming = new Person(' xiaoming ', 8)Copy the code

The prototype object is explained as shown

Prototype chain

  • 1. The concept

When we try to access the properties/methods of a JavaScript instance, it first searches for the instance itself; When it finds that the instance does not have a corresponding property/method defined, it searches for the instance’s prototype object instead. If it can’t find any of the prototype objects, it searches for the prototype object of the prototype object, and the trajectory of the search is called the prototype chain.

  • Graphic prototype chain

Note: Almost all objects in JavaScript are instances of Object at the top of the prototype chain, exceptObject.create(null)If you create an Object that doesn’t have any archetypes, it’s not an Object.

Deep copy of objects

  • 1. The concept

Copy an object that does not interfere with each other

  • 2. Method 1 json.stringify

PS: The downside is that you can’t handle functions, you can’t handle regees, etc., and you can only use this if your object is a strict JSON object.

  • 3. JSON. Stringify case
const list = { total: 101, limit: 4, page: 1, child: Parse (json.stringify (list)) // Complete const list2 = json.parse (list); = 3; list.child = ['kobe', 'james', 'yao', 'harden'] console.log(list2.child); / / [' Ming ', 'xiao gang', 'xiao bao', 'wah] the console. The log (list. Child); // ['kobe', 'james', 'yao', 'harden']Copy the code
  • 4. Deep copy by hand
Function deepClone(obj) {// Return if (typeof obj! == 'object' || obj === null) { return obj; } let copy = {} // If the object is an array, Constructor === Array) {copy = []} // Iterate the key for(let key in obj) {if(obj.hasownProperty (key)) {// Copy [key] = deepClone(obj[key])} else {copy[key] = obj[key]}} return copy}Copy the code