Often have a look; knock

1. Data hijacking object.defineProperty and proxy

/** * proxy Object.defineProperty */
//proxy Proxy comparison object.defineProperty
handler = {
  set(target, key, value) {
    console.log(key, "set");
    target[key] = value;
    return true; }};var target = {};
var proxydata = new Proxy(target, handler);

/** * data hijacking defineProperty */
function definePropertydata() {
  let _val = "";
  let _nameList = [];

  Object.defineProperties(this, {
    aname: {
      get() {
        return _val;
      },
      set(newVal){ _val = newVal; _nameList.push(_val); }},bname: {
      get() {
        return _val;
      },
      set(newVal){ _val = newVal; _nameList.push(_val); ,}}});this.getNameList = function() {
    return _nameList;
  };
}

var backDefineData = new definePropertydata();
backDefineData.aname = "test get aname";
backDefineData.bname = "test get bname";

console.log(backDefineData.getNameList());
Copy the code

2. Prototype prototype chain

/** * prototype prototype chain */
// Functions have two values: 1. Implementation concrete 2. As objects
// Functions are both functions and objects; both prototype and __proto__


// The relationship between stereotype and implicit stereotype
// Each constructor has a prototype property, from which all objects created by the constructor inherit.
// object.__ptoto__ == constructor. Prototype
// The implicit stereotype of an object is equal to the stereotype of the constructor that created the object

//
function Func() {
  this.name = 11;
} // Both prototype and __proto__
// Every object has __proto__

Func.prototype.func = function() {
  // console.log('222');
};

var nfunc = new Func();
nfunc.func();
nfunc.name;

console.log(nfunc.__proto__ == Func.prototype);

//nfunc.__proto__ == Func.prototype
//Func.prototype__proto__ == Object.prototype;
//Object.prototype.__proto__ == null

function Munc(name, sex) {
  this.name = name;
  this.sex = sex;
}

Munc.prototype.hellword = function() {
  console.log(this.name, this.sex);
};

var m_func = new Munc("111"."man");
m_func.hellword();
Copy the code

3. Implement a new feature

/** ** implements a new function */
///A. Implement A new 1. Create an empty object 2 object's __proto__ == caller's prototype 3. Change the point to Apply
// Note: methods on functions are mounted on __proto__
// The first step is empty object
// The second step is to pass the empty object's __proto__ == prototype through the prototype chain so that the empty object can call the method passed in
// The third step is to change the point of this via apply or call so that the empty object can access the property value of the passed object
function _new() {
  var _object = {};

  let constructor = [].shift.apply(arguments); // Arguments are array-like objects that need to be converted or array.prototype
  _object.__proto__ = constructor.prototype;

  let resback = constructor.apply(_object, arguments);

  return resback;
}
//B The second, more succinct method uses object.create to create a new Object
function _new() {
  var _object = {};
  let nModel = Array.prototype.shift.call(arguments);
  _object = Object.create(nModel);
  let res = nModel.apply(_object, arguments);
  return res;
}
Copy the code

Implement a call function

/** * implements a call function */
Function.prototype._call = function(object, ... arg) {
  object.fn = this;
  letbackfn = object.fn(... arg);delete object.fn;
  return backfn;
};
function f(name, age) {
  return this.value + name + age;
}
let newModel = { value: 100 };

console.log(f._call(newModel, 1.2));
//call bind apply
// Apply and call are similar, except that they take different parameters
// Apply parameter array or class array
The //bind() method creates a new function that, when called, sets its this keyword to the supplied value and, when called, provides a given sequence of arguments before any supply.
// Bind creates a new function that we have to call manually
Copy the code

5. The use of the valueOf

// Use of valueOf (automatically called when the value == <> + - */)
// The same toString priority valueOf; ToString favors showing valueOf favors operations
let age = {
  i: 1.valueOf: () = >{ age.i++; }};if (age == 1) {
  console.log("Judgment time automatically called!" + age);
}
Copy the code

6. Reduce calculates the maximum and minimum values

//reduce calculates the maximum and minimum values
let max = datalist.reduce((currentdata, item) = > {
  return currentdata.count >= item.count ? currentdata.count : item.count;
});
let min = datalist.reduce((currentdata, item) = > {
  return currentdata.count <= item.count ? currentdata.count : item.count;
});
Copy the code

7. Delete array or class array and merge keyword filter concat

let a = [
  { name: "aa".sex: "bb" },
  { name: "dd".sex: "bb" },
  { name: "ee".sex: "bb" },
  { name: "ff".sex: "bb"},];let b = [
  { name: "aa".sex: "bb" },
  { name: "bb".sex: "bb" },
  { name: "cc".sex: "bb"},];let find_data = a.map((item) = > item.name);
let new_data = b.filter((v) = >! find_data.includes(v.name));let result = a.concat(new_data);
console.log(result);
Copy the code

Regular expressions

// Regular expressions
// /xxxx/
// / XXX/I is case insensitive
// / XXX /g global search
// / XXX /m multi-line search
// [] expression [a-z] A to Z
/ / / ^ invert

// metacharacter \w ===[0-9a-z] \d===[0-9]

//n+ {1, infinity} demo:'abcd' => ['abcd']
//-- Greed mode
//n* {0, infinity} demo:'abcd' => ['abcd']['']
//n? {0} demo:' abCD '=> ['a']['b']['c']['d']['']
/ / n {1, 2} demo: 'abcd' = > [' ab '] [' CD ']
/ / ^ n n beginning
/ / n $n the end
/ /? =n matches immediately followed by n
/ /? ! N matches don't follow n

// Subexpression () /(a)(b)/ (a) the first expression (b) the second expression
// backreference \x x denotes the number of times \1/ (a)\1\1\1/ denotes as many times as it takes to fetch the first expression
// The subexpression has memory function and matches according to the rules of the subexpression
Copy the code

9. Recursive methods

function formatRouterTree(datalist) {
  let parentRouter = datalist.filter((pi) = > pi.pid == 0);
  let childrenRoter = datalist.filter((ci) = >ci.pid ! =0);
  dataTreelist(parentRouter, childrenRoter);
  // Recursive method
  function dataTreelist(parentRouter, childrenRoter) {
    parentRouter.map((p) = > {
      childrenRoter.map((c, i) = > {
        if (c.pid == p.id) {
          let _c = JSON.parse(JSON.stringify(childrenRoter));
          _c.splice(i, 1);
          dataTreelist([c], _c);

          if (p.children) {
            p.children.push(c);
          } else{ p.children = [c]; }}}); }); }return parentRouter;
}
Copy the code

10. Simulate VUE data bidirectional binding

<! DOCTYPE html><html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <div>
        <input type="text" v-wc="name" placeholder="Name" />
        <input type="text" v-wc="age" placeholder="Age" />
        <input type="text" v-wc="email" placeholder="email" />
        <input type="text" v-wc="tel" placeholder="tel" />
      </div>
      <div>
        <p>Name:<span>{{name}}</span> </p>
        <p>Age:<span>{{age}}</span></p>
        <p>Email:<span>{{email}}</span></p>
        <p>Tel:<span>{{tel}}</span></p>
      </div>
    </div>
  </body>
</html>

<script type="text/javascript" src="./src/libs/MVVM.js"></script>
<script>
  const app = new MVVM('#app', {name:'wzt'.age:'18'.email:'123'.tel:'44'});</script>


class MVVM {
  constructor(el, data) {
    this.el = document.querySelector(el);
    this._data = data;
    this.domdata = {};
    this.init();
  }
  init() {
    this.initData();
    this.initDom();
  }
  initDom() {
    this.bindInput(this.el);
    this.bindDom(this.el);
  }
  / / 1. Implement the data (the data corresponding to hijack) definePrototy | | proxy
  initData() {
    const _this = this;
    this.data = {};

    for (let key in this._data) {
      console.log(key);
      Object.defineProperty(this.data, key, {
        get() {
          console.log(1111);
          return _this._data[key];
        },
        set(newVal) {
          console.log(222);
          // Bind the value to the element_this.domdata[key].innerHTML = newVal; _this._data[key] = newVal; }}); }}//2. Capture input binding event keyUP value change data (find instruction such as V-model)
  bindInput(el) {
    const _allinputs = el.querySelectorAll("input");
    _allinputs.forEach((input) = > {
      const _findmodel = input.getAttribute("v-wc"); // Find the attribute value
      if (_findmodel) {
        // Bind events
        input.addEventListener(
          "keyup".this.handleInput.bind(this, _findmodel, input) ); }}); }handleInput(key, input) {
    const _value = input.value;
    this.data[key] = _value;
  }
  //3. Bind the changed value to page p (find {{}})
  bindDom(el) {
    const childnodes = el.childNodes;
    childnodes.forEach((item) = > {
      if (item.nodeType == "3") {
        const _value = item.nodeValue;
        if (_value.trim().length) {
          {{}}}
          let _valid = / \ {\ {(. +?) \} \} /.test(_value);
          if (_valid) {
            / / to find the KEY
            let _key = _value.match(/ \ {\ {(. +?) \} \} /) [1].trim();
            this.domdata[_key] = item.parentNode;
            // Find the node and assign the node
            item.parentNode.innerText = this._data[_key] || "";
          }
        }
      }
      item.childNodes && this.bindDom(item); }); }}Copy the code

11. Js inherits ES5 and ES6 differences

/ * * *@description Inheriting ES5 and ES6 differences *@auth  wzt 
 * @version 1.0 * /

// Inherit ES5 (prototype chain, constructor, composite inheritance)
function Student(name, age) {
  this.name = name;
  this.age = age;
}

Student.prototype.Setcourse = function() {
  console.log("aaa");
};

function Flamly(name, age, sex, height) {
  Student.call(this, name, age);
  this.sex = sex;
  this.height = height;
}

Flamly.prototype = Object.create(Student);
Flamly.prototype.constructor = Student;
var s1 = new Flamly("xx"."11");

/ / ES6 inheritance

class Person {
  // Call the class constructor
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  // Define general methods
  showName() {
    console.log("Call method of parent class");
    console.log(this.name, this.age); }}let p1 = new Person("kobe".39);
console.log(p1);
// Define a subclass
class Student extends Person {
  constructor(name, age, salary) {
    super(name, age); // Call the parent constructor with super
    this.salary = salary;
  }
  showName() {
    // Define methods in the subclass itself
    console.log("Calling a subclass's method");
    console.log(this.name, this.age, this.salary); }}let s1 = new Student("wade".38.1000000000);
console.log(s1);
s1.showName();

Copy the code