JavaScript Written Section

This article shares 12 frequently asked JavaScript interview questions, including handwriting and common re.

Implement the anti-skid function (debounce)


The mechanism of the anti-shake function is that the callback is executed n seconds after the event is triggered. If the event is triggered again within this n seconds, the timer is re-timed.

The difference with the throttling function can be directly seen in this animation implementation.

Simplified handwritten version

// Const debounce = (fn,delay)=>{let timer = null;
    return(... args)=>{ clearTimeout(timer); timer =setTimeout(()=>{
        fn.apply(this,args)
        },delay);
    };
};
    
Copy the code

Application scenario:

  • Button submit scenario: Prevent multiple button submissions and execute only the last one
  • Server validation scenario: Form validation requires server cooperation, only the last time of a series of input events are performed, and search for associative words is similar

For survival, use lodash. Debounce

Implement throttling functions


Shaking function principle: specified in a unit of time. The function can only be fired once. If this function fires multiple times per unit time, only one will take effect.

// Write a simplified version

Const throttle = (fn,delay = 500) =>{let flag = true;
    return(... args) =>{if(! flag)return;
        flag = false;
        setTimeout(() => {
        fn.apply(this,args)
        },delay);
    };
};
Copy the code

Application scenario:

  • Drag and drop scenario: Only once in a fixed time to prevent uHF trigger position changes
  • Zoom scenario: Monitor the browser resize
  • Animated scenes: Avoid triggering animations multiple times in a short period of time to cause performance problems

A deep clone (deepclone)


Simple version:

const newObj = JSON.parse(JSON.stringify(oldObj));
Copy the code

Limitations: 1. It cannot clone special objects such as functions and RegExp

2. Discard constructor for objects; all constructors will point to objects

Error: object with circular reference

Implement Event (Event Bus)


Event Bus is not only the cornerstone of each module in node, but also one of the dependent means of communication of front-end components. It also involves the subscription-publish design pattern, which is a very important foundation.

Simple version:

class EventEmeitter {
    constructor(){ this._events = this._events || new Map(); / / storage event callback key/value pair this. _maxListeners = this. _maxListeners | | 1 o; }} // Trigger nametypeThe event EventEmeitter. Prototype. Emit =function(type. args){lethander; Handler = this._events.get(this._events.get);type);
    if (args.length > 0) {
        hander.apply(this,args);
    }else{
        handler.call(this);
    }
    return true; }; // Listen nametypeEvent EventEmeitter. Prototype. AddListener =function(type, fn) {/ / willtypeThe event and its corresponding fn function are stored in this._eventsif(! this._events.get(type)) {
        this._events.set(type,fn); }};Copy the code

Implement instanceOf


/ / simulation instanceoffunctioninstance_of(L,R){ var O = R.prototype; // select * from R where L = l. __proto__; // Take the implicit prototype of Lwhile (true) {
        if (L === null) return false;
        if(O === L) (O === Ltrue
        return true; L = L.__proto__; }}Copy the code

Simulation of the new


The new operator does these things:

  • He creates an entirely new object
  • It will be linked to [[Prototype]] (i.e. __proto__)
  • It makes this point to the newly created object
  • Each object created with new will eventually be linked to the function’s Prototype object by [[Prototype]]
  • If the Function does not return Object type Object(including Function, Array, Date, RegExg, Error), then the Function call in the new expression returns the Object reference
// objectFactory(name,'cxk'.'18')
function objectFactory(){
    const obj = new object();
    const Constructor = [].shift.call(arguments);
    
    obj.__proto__ = Constructor.prototype;
    
    const ret = Constructor.apply(obj,arguments);
    
    return typeof ret === "object" ? ret : obj;
}
Copy the code

Implementing a call


What did Call do:

  • Sets a function as a property of an object
  • Execute & to remove the function
  • Specify this to a function and pass the given argument to execute the function
  • If no person parameter is passed, the default point is window
// Simulate call bar.myCall (null); // Implement a call method; Function.prototype.myCall =function(context){// here the context is not considered context.fn = this;let args = [];
    for (leti = 1,len = arguments.length,i < len; i++){ args.push(arguments[i]); } context.fn(... args);letresult = context.fn(... args); delete context.fn;return result;
};
Copy the code

Implement the Apply method


Apply principle is very similar to Call, not many mastiffs

/ / simulate the apply Function. The prototype. Myapply =function(context,arr){
    var context = Object(context) || window;
    context.fn = this;
    
    var result;
    if(! arr){ result = context.fn(); }else{
        var args = [];
        for(var i = 0,len = arr.length; i < len; i++){ args.push("arr["+ i +"]");
        }
        result = eval("context.fn("+ args + ")");
    }
    delete context.fn;
    return result;
}
Copy the code

To realize the bind


What does a bind implementation do

  • Return a function, bound to this, passing preset arguments
  • The function returned by bind can be used as a constructor. So the constructor should invalidate this, but the pass-through argument is still valid
// MDN implementationif(! Function.prototype.bind) { Function.prototype.bind =function(oThis) {
    if(typeof this ! = ='function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }

    var aArgs   = Array.prototype.slice.call(arguments, 1),
        fToBind = this,
        fNOP    = function() {},
        fBound  = function() {
          // this instanceof fBound === trueThe returned fBound is called as the constructor for newreturnfToBind.apply(this instanceof fBound ? This: oThis, / / get a call (fBound) ginseng. Bind returns the function into the participation is often so pass aArgs. Concat (Array) prototype. Slice. The call (the arguments))); }; // Maintain the prototype relationshipif(this.prototype) {} // The downstream code makes fbound. prototype an instance of fNOP, so // If the returned fBound is used as the constructor for new, the new object is passed as this. The __proto__ of the new object is an instance of fNOP fbound.prototype = new fNOP();returnfBound; }; } Copy the code to see more details in JavaScriptbindSimulation implementation of# 12Mock the object.create object.create () method to create a new Object, using an existing Object to provide the __proto__ of the newly created Object. / / simulation Object. The createfunction create(proto) {
  function F() {}
  F.prototype = proto;

  return new F();
}
Copy the code

Simulation Object. The create


The object.create () method creates a new Object, using an existing Object to provide the __proto__ of the newly created Object.

/ / simulation object. The createfunction create(proto){
    function F(){
        F.prototype = proto;
        
        returnnew F(); }}Copy the code

Parse URL Params into objects


let url = 'http://www.domain.com/?user=anonymous&id=123&id=456&city=%E5%8C%97%E4%BA%AC&enabled'; ParseParam (url) /* Result {user:'anonymous'(id: [123, 456]); (id: [123, 456]);'Beijing'// Enabled:true, // not specifying the value key convention istrue} * /Copy the code

Convert to a hump name

var s1 = "get-element-by-id"// Convert to getElementByIdCopy the code
var f = function(s){
    return s.replace(/-\w/g,function(x){
      returnx.slice(1).toUpperCase(); })}Copy the code

This article is mainly some basic knowledge, hoping to help those who do not have a good foundation of peers. Come on ~ ~ ~ ~ ~ ~