• I can’t figure it out all the time

What is a constructor

Constructor is an attribute of prototype. When a function is defined, the JS engine adds the prototype to the function and the constructor attribute points to the function reference

Ps:

Overriding prototype therefore loses the original constructor. As discussed below, for standardized development purposes, overriding an object prototype typically requires re-assigning constructor to ensure that the type of the object instance is not tampered with.

Ii. What is a prototype and what is a prototype chain

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, > <title>Document</title> </head> <body> <! The object.getProtoTypeof () method returns the Prototype of the specified Object (that is, the internal [[Prototype]] property). --> <script> let arr = ['abc'] console.log(arr.concat('123'))//0: "abc" 1: "123" let hh = {} let gg = {} // __proto__ understand as father console.log(object.getProtoTypeof (hh) == object.getProtoof (gg))// True let bb = {name :" baby "}; console.log(bb); // Console. log(bb.hasownProperty ("name")) with proto's father; The //true // hasOwnProperty() method returns a Boolean value indicating whether the object has the specified property in its own properties (that is, whether it has the specified key). Create (proto, [propertiesObject]) //proto The prototype Object of the newly created Object. Create a prototype of the object that indicates that the object to inherit // propertiesObject(optional) is also an object, Let cc = object.create (null, {name: {value: "Lalala"}}) console.log(cc)// No console.log(cc.hasownProperty ("name"))// cc.hasownProperty is not a function </script> </body> </html>Copy the code

Proto is an object that finds a connection point for properties in a parent that has a bunch of built-in properties that can be inherited

Add methods to the prototype

Let smailDog = {bigDog() {console.log(' hairy big fat dog ')}, Log (smailDog)}} console.log(smailDog) // ƒ bigDog() ƒ xiaoDog() {console.log(" xiao ")} smaildog.xiaodog (); // Labrador labrador labrador labrador labradorCopy the code

Functions have more than one parent

The constructor has a prototype attribute

Instances have no Prototype attribute

Constructors have two parents: prototype and proto, but their usage scenarios are different

Both User and instance newUser refer to the same stereotype so instances can use the show method

The newUser instance can only find a prototype through __proto__ because it has no prototype

Ps:

These two elders are not the same and these two elders are also objects to remember

Prototype and proto service scenarios :(they are both prototypes)

  1. Prototype typically serves instantiated objects
  2. Proto, on the other hand, usually serves the constructor itself

Object constructor

Print:

console.dir(Object) let xiaoMing = new Object(); Object.prototype.show = function() {console.log(' console.log ')} xiaoMing. // There is no Xiao Ming in the canyon anymoreCopy the code

Constructor instantiations can use the methods in Object.prototype

Prototype –proto– prototype –proto– prototype –proto– prototype –proto– prototype

instructions

console.log(User.prototype.proto == User.proto.proto)//true

__proto__ can be thought of as looking for a parent join point

Look at the Object. The prototype

There is no parent in it

console.dir(Object.prototype.proto)//null

Null is the top prototype

<script> console.dir(Object) let xiaoMing = new Object(); Object.prototype.show = function() {console.log(' console.log ')} xiaoMing. Function User() {} console.dir(User) console.log(user.proto__ == user.__proto__.__proto__)//true console.dir(Object.prototype) console.dir(Object.prototype.__proto__)//null let mingQi = new Object(); mingQi.show(); User.show(); console.dir(Object.__proto__) console.dir(Object.__proto__.__proto__)//null </script>Copy the code

The prototype embodiment of the constructor

let arr = []//new Array console.log(Array.prototype) console.log(arr.__proto__ == Array.prototype) let obj = {}//new Object console.log(obj.__proto__ == Object.prototype) let bool = true //new Boolean console.log(bool.__proto__ == Boolean.prototype) let str = ""//new String console.log(str.__proto__ == String.prototype) String.prototype.show = Function () {console.log(' call the show method ')} str.show(); </script>Copy the code

Custom prototype Settings

// object.setPrototypeof (), which sets a prototype for an existing Object and returns a new Object // Takes two arguments: the first is the existing Object and the second is the prototype Object. Let xm = {name :' xiaoming '}; Let xmParent = {name:' xmParent ', show(){ console.log('parent method:' + this.name) } } console.dir(xm) Object.setPrototypeOf(xm,xmParent)// parent Method: xiao Ming xm show (); xmParent.show(); //parent method: console.log(object.getPrototypeof (xm))// {name: "console.log ", show: ƒ} // object.getProtoTypeof () returns the Prototype of the specified Object (that is, the internal [[Prototype]] attribute). </script>Copy the code

A reference to constructor in the prototype

function User(name) { this.name = name; } // User.prototype.show =function(){ // console.log('show:'+ this.name) // } // let lisi = new User. The prototype. The constructor (' bill ') / / equivalent to a new Object (' bill ') / / console log (lisi) / / User {name: "bill"} / / lisi. The show (); Prototype = {constructor: //show (); //show (); User, show() { console.log(this.name) }, The view () {the console. The log (' view of the User. The prototype method ')}} let lisi = new User. The prototype. The constructor (' bill ') / / is equal to the new Object (' lisi ') console.log(lisi); lisi.show(); //lisi.show is not a function () {// constructor: User </script>Copy the code

Find the constructor by prototype. The constructor instantiates the new object

Custom methods create new objects new User(‘ ‘) is replaced by custom functions

<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <title>Document</title> </head> <body> <script> // function User(name) {// this.name = name; / / / /} let lisi = new User. The prototype. The constructor (' bill ') / / equivalent to a new Object (' bill ') / / the console. The log (lisi) / / {name: } // function User(name) {// this.name = name, // this.show = function () {// console.log(this.name); / / / / / /}} let hd = new User (' labrador ') / / console log (hd) / / {name: "labrador" show: ƒ ()} / / / / to create a new object xj now = {name: ƒ ()} // function createByObject(obj,... // const constructor = object.getProtoTypeof (obj).constructor // return new constructor(... The args) / / the new User. The prototype. The constructor (' bill ') / / equivalent to a new Object (' bill ') / / / /} let mq = createByObject (hd, '7' styles); // console.log(mq.name)// ming7 // mq.show(); Function User(name) {this.name = name} user. prototype = {constructor: User, show(){ console.log(this.name); }} let hd = new User(' labore ') console.log(hd)//{name: "labore" show: ƒ ()} function createByObject(obj,... Constructor = object.getProtoTypeof (obj).constructor return const constructor = object.getProtoTypeof (obj).constructor return new constructor(... The args) / / the new User. The prototype. The constructor (' bill ') / / equivalent to a new Object (' bill ')} let mq = createByObject (hd, '7' styles); The console. The log (mq) name) seven mq. / / styles show (); </script> </body> </ HTML >Copy the code

The embodiment of prototype inheritance:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <body> <script> let a = {name:'a'} let c = {name:'c'} let b = {name:'b', show(){ console.log(this.name) }, view(){ console.log('view method') } } Object.setPrototypeOf(a,b) Object.setPrototypeOf(c,b) console.log(a) a.show(); c.show(); a.view(); c.view(); </script> </body> </html>Copy the code

Object.isPrototypeOf

  • Explicitly determine whether an object is part of a chain of other object prototypes
// JS isPrototypeOf() method: Let a = {} let b = {} let c = {} // console.log(a.isprototypeof (b)) / / false Object is a part of a/b Object prototype chain/console log (Object. The prototype. IsPrototypeOf (a)) / / true Object. The prototype is the top of the a Object.setPrototypeOf(b,c) Object.setPrototypeOf(a,b) console.log(b.isPrototypeOf(a)) console.log(c.isPrototypeOf(a)) console.log(c.isPrototypeOf(b)) </script>Copy the code

Difference between in and hasOwnProperty detection

In will go up the prototype chain and hasOwnProperty will only go up the current object

Let one = {name: ' '} let tow = {url: 'www.abc.com'} object.prototype. web = "I love you" // "name" means key // console.log("name" in one)//true // console.log("url" in one)//false Object.setPrototypeOf(one, tow) console.log("url" in one)//true console.log("web" in one)//true console.log("web" in tow)//true Console. log(one.hasownProperty ('name'))//true Whether the property is on its own console.log(one.hasownProperty ('url'))//false console.log(one.hasOwnProperty('web'))//false // for(const key in one){ // console.log(key)//name url web // } for (const key in one) {// console.log(key)// Inherits name URL web if (one.hasownProperty (key)) console.log(key)// Does not inherit name}Copy the code

The sort () method

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, /> <title>Document</title> </head> <body> <! The -- sort() method is used to sort the elements of an array and return an array --> <script> //1. // let arr = [2, 1, 3, 5, 4]; // arr = arr.sort((n1, n2) => { // // return -1; // // return 0 or 1 // Return positive values in the same order // console.log(n1, n2); // return n2 - n1; // // n2-n1 from large to small // // n1-n2 from small to large //}); // console.log(arr); //[5, 4, 3, 2, 1] // var arr = ['General','Tom','Bob','John','Army']; // var resArr = arr.sort(); // console.log(resArr); / / output [" Army ", "Bob", "General", "John", "Tom"] / / var arr2 = 30,10,111,35,1899,50,45 []; // var resArr2 = arr2.sort(); // console.log(resArr2); Sort [10, 111, 1899, 30, 35, 45, 50] Alphabetical order (sort the default sort) var arr = [" za ", "zb", "a", "b", "xc", "xa"]. arr.sort(); console.log(arr); [" A ", "b", "XA "," XC ", "ZA ", "zb"] // 3 Var obj = [{name: "Lucy ", num: 400}, {name:" Nancy ", num: 110}, {name: "Nancy" "maria", num: 200 }, { name: "sb" }, { name: "zhu" }, { name: "dog", num: 'abc' } ]; obj.sort(compare("num")); console.log(obj); // 0: {name: "nancy", num: 110} // 1: {name: "maria", num: 200} // 2: {name: "lucy", num: 400} // 3: {name: "sb"} // 4: { name: "zhu" } // 5: { name: "dog", num: The argument in "ABC"} // compare() must be the attribute name of the object, and the objects you are comparing should have that attribute name, Function compare(property) {return function (a, B) {// value1-value2 ascending // value2-value1 descending var value1 = a[property]; var value2 = b[property]; return value1 - value2; Ascending and small to large}} / / var arr5 = [{id: 10}, {id: 5}, {id: 6}, {id: 9}, {id: 2}, {id: 3}]. arr5.sort(function (a, b) {// return a.id - b.id }) console.log(arr5); / / output new sorting / / {2} id: / / / / {id: 3} {5} id: / / 6} {id: / / 9} {id: / / {10} id: / / 4. Sort according to multiple attribute values of objects in the array, multi-condition sort; var arr6 = [{ id: 10, age: 2 }, { id: 5, age: 4 }, { id: 6, age: 10 }, { id: 9, age: 6 }, { id: 2, age: 8 }, { id: 10, age: 9 }]; Arr6.sort (function (a, b) {if (a.id === b.id) { Return b.age - a.age} else {return a.id - b.id}}) console.log(arr6); / / sorting/new / {8} id: 2 age: / / {id: 5, age: 4} / / {10} id: 6, age: / / {id: 9, age: 6} / / 9} {id: 10, age: / / {id: Let arrDiy = [3, 15, 8, 29, 102, 22] console.log(arrDIy.sort ()) // 0: 102 // 1: 15 // 2: 22 // 3: 29 // 4: 3 // 5: 8 / / in accordance with the unicode sorting will be for the toString () method / / [" 3 ", "15", "eight" and "29", "102", "22"] / / the ranking results for the first time: ["15","102","29","22","3","8"] [" 102 ", "15", "22", "29", "3", "eight"] / / digital = = > > capital letters lowercase = > = "Chinese" var newArr [3, 15, 8, 29, 102, 22] newarr.sort (function (a, b) {// console.log(' sort: '+ a +"," + b) console.log(a +" -" + b +" =" + (a-b)) // look at the expression like the first minus the second but the result is not // 15-3 =12 3 15 // 8 - 15=-7 8 15 // 29-8 =21 8 29 // 102-29 =73 29 102 // 22-102 =-80 22 102 return a-b}) Console. log(newArr) // [3, 8, 15, 22, 29, 102] // Underlying algorithm: </script> </body> </ HTML >Copy the code

Use method

For example: you don’t have a car your parents don’t own a car your grandparents don’t have a car your neighbor is me I have a Mercedes You can borrow my car to drive

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, > <title>Document</title> </head> <body> <script> This. name = "car "; } var benz = new Car(); console.log(benz.name); // add object.setProtoTypeof (Benz, {name: "Benz ", price: "23456"}); // add object.setProtoTypeof (Benz, {name:" Benz ", price: "23456"}); / / __proto__ : {name: "cars," price: "23456"} the console. The log (Benz. Name); / / car console. The log (Benz. Price); // let hh = {data: [12, 50, 60, 42, 10, 5]} Object.setProtoTypeof (hh, {// Add method Max () {return this.data.sort((x, y) => y-x)[0]; }}) console. The log (hh. Max ()) / / 60 let xj = {lessons: {js: 87, PHP: 100, node: 99, Linux: 45}, / / get the date () {/ / according to get what want? // get date(){//why? Get data(){//why get? Return object.values (this.lessons)}} console.log(hh.max.apply(xj))// If xj does not have data attributes, then xj adds a score to the return result of the method </script> </body> </html>Copy the code

Parameters passed by call and apply can be converted by extended operators

Let mq = {data:[1,2,336,445,52,12,120]} console.log(math.max (mq.data))//NaN Console. log(math.max. apply(null,mq.data))//445 // Console. log(math.max. call(null,... mq.data))//445 let xm = { lessons:{ math:100,english:0,huaxue:20,shengwu:95 } } console.log(Math.max.apply(null,Object.values(xm.lessons)))//100 console.log(Math.max.call(null,... Object.values(xm.lessons)))//100Copy the code

Changing the constructor stereotype is not inheritance

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, "> <title>Document</title> </head> <body> <script> function Menber(){} function Admin(){} function User(){ } User.prototype = { constructor:User, name:function(){ console.log('user.name'); } } let a = new User(); a.name() Admin.prototype = User.prototype; Admin.prototype.role = function() { console.log('admin.role'); } Menber.prototype = User.prototype; Menber.prototype.role = function() { console.log('Menber.role'); } let b = new Admin(); b.role(); Let c = new Menber(); c.role(); //Menber.role </script> </body> </html>Copy the code

Inheritance is the inheritance of archetypes

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, "> <title>Document</title> </head> <body> <script> function Menber(){} function Admin(){} function User(){ } User.prototype = { constructor:User, name:function(){ console.log('user.name'); } } let a = new User(); a.name() // Admin.prototype.__proto__= User.prototype; // Admin.prototype.role = function() { // console.log('admin.role'); Function admin.prototype = object.create (user.prototype) admin.prototype. role = function(); { console.log('admin.role'); } Menber.prototype.__proto__= User.prototype; Menber.prototype.role = function() { console.log('Menber.role'); } let b = new Admin(); b.role(); //admin.role let c = new Menber(); c.role(); //Menber.role </script> </body> </html>Copy the code

The problem of multiple inheritance

The Admin instance wants to use the methods in the credit and Request prototypes

The member instance wants to use the credit and Request archetypes plus the methods in the member

But Admin does not need to use the member prototype methods

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, > <title>Document</title> </head> <body> <script> // set constructor not to constructor; // set constructor not to constructor Object.defineProperty(child.prototype, 'constructor', { value: child, enumerable: False})} function Credit() {inherit(Credit, Address) Credit. Prototype. Total = function () {console.log(' console.log '); } function Request() {} Inherit (Request, Credit) request.prototype. ajax = function () {console.log(); } function Address() {// if (function Address() {// if (function Address() {// if (function Address() {// if (function Address() {// if (function Address() {// if (function Address() {// if (function Address() {// if (function Address() {// Inherit (Credit, Address) Address. Prototype. GetAddress = function () {the console. The log (' access to Address); } function user (name, age) {this.name = name; this.age = age; } inherit(User, Request); User.prototype.show = function () {console.log(' hello, prototype '); } function Admin(name, age) {// Initialize instance data user.call (this, name, age); } inherit(Admin, User) // function Address(){ // } // inherit(Credit,Address) // Address.prototype.getAddress = function(){ // Console. log(' get address '); } let newAdmin = newAdmin (" newAdmin ", 123); console.log(newAdmin); // {name: "static ", age: 123} newadmin.ajax (); Newadmin.total (); Newadmin.getaddress (); newadmin.getAddress (); Function Member(name, age) {// Call (this, name, age); Inherit (Member, User) let newMember = newMember (' inherit ', 12); inherit(Member, User) let newMember = newMember (' inherit ', 12); console.log(newMember); newMember.getAddress(); newMember.ajax(); newMember.total(); </script> </body> </html>Copy the code

Implement multiple inheritance using mixins

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, > <title>Document</title> </head> <body> <script> // set constructor not to constructor; // set constructor not to constructor Object.defineProperty(child.prototype, 'constructor', { value: child, enumerable: False})} const Credit = {total() {console.log(' console.log '); }} const Request = {ajax () {console.log(" Request background "); }} const Address = {getAddress(){console.log(' getAddress '); Function user (name, age) {this.name = name; this.age = age; } user.prototype. show = function () {console.log(' hello, prototype '); } function Admin(name, age) {// Initialize instance data user.call (this, name, age); } inherit(Admin, User) // inherit(Admin, User) Request) // console.log(Admin.prototype); //{total: ƒ, ajax: ƒ, constructor: ƒ} let newAdmin = newAdmin (" Beijing ", 123); console.log(newAdmin); // {name: "static ", age: 123} newadmin.ajax (); Newadmin.total (); // newadmin.getAddress (); Function Member(name, age) {// Call (this, name, age); } inherit(Member, User) Member. The prototype = Object. The assign (Member. The prototype, Credit, Request, Address) let newMember = new Member (' la-la-la, 12); console.log(newMember); newMember.getAddress(); newMember.ajax(); newMember.total(); newMember.show(); </script> </body> </ HTML >Copy the code

Mixin’s internal inheritance with the super keyword

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, > <title>Document</title> </head> <body> <script> // set constructor not to constructor; // set constructor not to constructor Object.defineProperty(child.prototype, 'constructor', { value: child, enumerable: False})} const Request = {ajax () {return "Request background "; Prototype const Credit = {__proto__:Request, Total () {// console.log(this); //Admin {name: "", age: 123}.totol (), which will find the total in admin.prototype. This is essentially the Credit constructor object that has ajax on Request (). Console.log (this.__proto__. Ajax () + 'stat score '); // console.log(super.ajax() + 'stat score '); }} const Address = {getAddress(){console.log(' getAddress '); Function user (name, age) {this.name = name; this.age = age; } user.prototype. show = function () {console.log(' hello, prototype '); } function Admin(name, age) {// Initialize instance data user.call (this, name, age); } inherit(Admin, User) // inherit(Admin, User) Request) // console.log(Admin.prototype); //{total: ƒ, ajax: ƒ, constructor: ƒ} let newAdmin = newAdmin (" Beijing ", 123); console.log(newAdmin.ajax());; Newadmin.total (); </script> </body> </ HTML >Copy the code