1- Functions of anti-shake and throttling

* * * debounce: function buffs * @params * func: the task to be performed * wait: how often the operation is performed "default :300ms" * immediate: control the trigger boundary "default :false End boundary True start boundary "* @return * proxy handler function, handler function will be triggered frequently, frequent execution; * Inside the function, the func control we want to operate on is executed only once; * /
const debounce = function debounce(func, wait, immediate) {
    if (typeoffunc ! = ="function") throw new TypeError('func must be an function! ');
    if (typeof wait === "boolean") immediate = wait;
    if (typeofwait ! = ="number") wait = 300;
    if (typeofimmediate ! = ="boolean") immediate = false;
    let timer = null;
    return function proxy(. params) {
        letnow = ! timer && immediate, result;if (timer) clearTimeout(timer);
        timer = setTimeout(() = > {
            // Clear the last timer
            clearTimeout(timer);
            timer = null;
            // Comply with the execution of the last "trigger at the end boundary"
            if(! immediate) result = func.call(this. params); }, wait);// Match the first immediate execution of "trigger at the beginning boundary"
        if (now) result = func.call(this. params);return result;
    };
}

const handle = function handle(ev) {
    console.log(this, ev);
};
submit.onclick = debounce(handle, true);
Copy the code
/* * throttle: function throttling * @params * func: the final task to perform * wait: trigger frequency "default :300ms" * @return * proxy processing function */
const throttle = function throttle(func, wait) {
    if (typeoffunc ! = ="function") throw new TypeError('func must be a function! ');
    wait = +wait;
    if (isNaN(wait)) wait = 300;
    let timer = null,
        previous = 0;
    return function proxy(. params) {    
        let now = +new Date,
            remaining = wait - (now - previous),
            result;
        if (remaining <= 0) {
            // The interval has exceeded WAIT, so we execute immediately
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            previous = now;
            result = func.call(this. params);return result;
        }
        // If there is no timer, it means that the last time was not executed, and we are starting the next time
        if(! timer) { timer =setTimeout(() = > {
                clearTimeout(timer);
                timer = null;
                previous = +new Date;
                result = func.call(this. params); }, remaining); }return result;
    };
}

const handle = function handle(ev) {
    console.log(this, ev);
    // console.log('OK');
};
window.onscroll = throttle(handle);
Copy the code

2-hasPubProperty

Requirement: Encapsulate methods that test whether a property is public to an object

Idea 1: Check for properties that are not private => in Check for private properties => hasOwnProperty

function hasPubProperty(obj, attr) {
    return (attr inobj) && ! obj.hasOwnProperty(attr); }// Disadvantages: Cannot detect both private and public attributes
Copy the code

Idea 2: The current property is the public property of the object, regardless of whether it is private or not

Object.prototype.hasPubProperty = function hasPubProperty(attr) {
    // Find the current Object's prototype and keep looking up until you find Object.prototype;
    // Whenever a prototype object has an attr attribute, that attribute is the object's public attribute
    let proto = Object.getPrototypeOf(this);
    while (proto) {
        if (proto.hasOwnProperty(attr)) return true;
        proto = Object.getPrototypeOf(proto);
    }
    return false;
};
let obj = {
    name: 'obj'.toString(){}};console.log(obj.hasPubProperty('name')); //=>false
console.log(obj.hasPubProperty('toString')); //=>true 
Copy the code

3- Override built-in new

Requirements:

function Dog(name) {
    this.name = name;
}
Dog.prototype.bark = function () {
    console.log('wangwang');
}
Dog.prototype.sayName = function () {
    console.log('my name is ' + this.name);
}
/* let sanmao = new Dog('小 black '); sanmao.sayName(); sanmao.bark(); * /
function _new() {
    Finish your code
}
let sanmao = _new(Dog, 'black');
sanmao.bark(); //=>"wangwang"
sanmao.sayName(); //=>" My name is black"
console.log(sanmao instanceof Dog); //=>true
Copy the code

What does new do

  1. Let this in the constructor point to the instance object
  2. This.xxx = XXX sets private properties and methods for instance objects
  3. If the constructor does not return or returns a primitive value, the created instance object is returned. If an object is returned, the object is returned by itself
const _new = function _new(Ctor, ... params) {
    // 1. Format check: function & has prototype object & not Symbol/BigInt
    if (typeofCtor ! = ="function") throw new TypeError(`${Ctor}is not a constructor! `);
    let name = Ctor.name,
        proto = Ctor.prototype,
        obj,
        result;
    if (/^(Symbol|BigInt)$/i.test(name) || ! proto) {throw new TypeError(`${name}is not a constructor! `);
    }
    
    // 2. Create an instance of the current class
    obj = Object.create(proto);
    
    // 3. Execute the constructor like a normal function, but this needs to point to the created instance objectresult = Ctor.call(obj, ... params);If no value is written, or if the value is original, we return the instance object by default.
    // If an object is returned, the object is returned.
    if(result ! = =null && /^(object|function)$/i.test(typeof result)) return result;
    return obj;
};
let sanmao = _new(Dog, 'black');
sanmao.bark(); //=>"wangwang"
sanmao.sayName(); //=>" My name is black"
console.log(sanmao instanceof Dog); //=>true
Copy the code

4-queryURLParams

Need: get the question mark parameter information in the URL address (hash information)

Create a TAB, assign the url string to href, deconstruct the hash and search, and then process the string

/* * @params * attr: Need to get information about this attribute * @return * specific attribute information value * the object containing all information */
String.prototype.queryURLParams = function queryURLParams(attr) {
    attr = attr + ' '; 
    let obj = {},
        link = document.createElement('a');
    link.href = this;
    let {
        hash,
        search
    } = link;
    if (hash) obj['_HASH'] = hash.substring(1);
    if (search) {
        search.substring(1).split('&').forEach(item= > {
            let [key, value] = item.split('=');
            obj[key] = value;
        });
    }
    if(attr ! = ="undefined") return obj[attr];
    return obj;
};

let url = "http://www.zhufengpeixun.cn/?name=leon&age=18#amazing";
console.log(url.queryURLParams("name")); //=> "leon"
console.log(url.queryURLParams("_HASH")); //=> "amazing"
console.log(url.queryURLParams()); //=> {_HASH: "amazing", name: "leon", age: "18"}
Copy the code

Idea 2: Regex

/* * @params * attr: Need to get information about this attribute * @return * specific attribute information value * the object containing all information */
String.prototype.queryURLParams = function queryURLParams(attr) {
    attr = attr + ' ';
    let obj = {};
    this.replace(/#([^?=&#]+)/g.(_, $1) = > obj['_HASH'] = $1);
    this.replace(/([^?=&#]+)=([^?=&#]+)/g.(_, $1, $2) = > obj[$1] = $2);
    if(attr ! = ="undefined") return obj[attr];
    return obj;
};

let url = "http://www.zhufengpeixun.cn/?name=leon&age=18#amazing";
console.log(url.queryURLParams("name")); //=> "leon"
console.log(url.queryURLParams("_HASH")); //=> "amazing"
console.log(url.queryURLParams()); //=> {_HASH: "amazing", name: "leon", age: "18"}
Copy the code

5 – hand tore the call

Function.prototype.call = function call(context, ... params) {
    / / this - > fn context - > obj params - > [10, 20]
    if (context == null) context = window;
    if (!/^(object|function)$/i.test(typeof context)) context = Object(context);
    let key = Symbol(),
        result;
    context[key] = this; result = context[key](... params);delete context[key];
    return result;
};

const fn = function fn(x, y, ev) {
    console.log(this, x, y, ev);
    return x + y;
};
let result = fn.call('AA'.10.20);
console.log(result); // {"AA", Symbol(): ƒ} 10 20 undefined
Copy the code

6 – hand tore the apply

Closure preservation function “kerochemical function” => preprocessing thought

Function.prototype.bind = function bind(context, ... params) {
    return (. args) = > {
        return this.call(context, ... params.concat(args)); }; };Copy the code