1024programmer Java “Intermediate and Senior Front-end Interview” JavaScript handwritten code invincible secrets (recommended)

“Intermediate and Senior Front-end Interview” JavaScript handwritten code invincible secrets (recommended)

1. Implement a new operator

The new operator does these things:

  1. It creates a completely new object.
  2. It will be executed [[Prototype]] (that is, __proto__) link.
  3. It makes this point to the newly created object. .
  4. Each object created through new will eventually be [[Prototype]] linked to the prototype object of this function.
  5. If the function does not return the object type Object (including Functoin, Array, Date, RegExg, Error), then the function call in the new expression will return the object reference.
 function New(func) {
  var res = {};
  if (func.prototype !== null) {
   res.__proto__ = func.prototype;
  }
  var ret = func.apply(res, Array.prototype.slice.call(arguments, 1));
  if ((typeof ret === "object" || typeof ret === "function") && ret !== null) {
   return ret;
  }
  return res;
 }
 var obj = New(A, 1, 2);
 // equals to
 var obj = new A(1, 2);

 

2. Implement a JSON.stringify

JSON.stringify(value[, replacer [, space]]):

  1. Boolean | Number | String type will be automatically converted to the corresponding primitive value.
  2. undefined, any function, and symbol will be ignored (when appearing in the property value of a non-array object), or converted to null (when appearing in an array).
  3. Non-enumerable properties will be ignored
  4. If the attribute value of an object refers back to the object itself in some indirect way, that is, a circular reference, the attribute will also be ignored.
 function jsonStringify(obj) {
  let type = typeof obj;
  if (type !== "object") {
   if (/string|undefined|function/.test(type)) {
    obj = '"' + obj + '"';
   }
   return String(obj);
  } else {
   let json = []
   let arr = Array.isArray(obj)
   for (let k in obj) {
    let v = obj[k];
    let type = typeof v;
    if (/string|undefined|function/.test(type)) {
     v = '"' + v + '"';
    } else if (type === "object") {
     v = jsonStringify(v);
    }
    json.push((arr ? "" : '"' + k + '":') + String(v));
   }
   return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}")
  }
 }
 jsonStringify({x : 5}) // "{"x":5}"
 jsonStringify([1, "false", false]) // "[1,"false",false]"
 jsonStringify({b: undefined}) // "{"b":"undefined"}"

 

3. Implement a JSON.parse

JSON.parse(text[, reviver])

Used to parse JSON strings and construct Javascript values ​​or objects described by strings. Provides an optional reviver function to perform transformations (operations) on the resulting object before returning.

3.1 The first method: call eval directly

 function jsonParse(opt) {
  return eval('(' + opt + ')');
 }
 jsonParse(jsonStringify({x : 5}))
 // Object {x: 5}
 jsonParse(jsonStringify([1, "false", false]))
 // [1, "false", falsr]
 jsonParse(jsonStringify({b: undefined}))
 // Object { b: "undefined"}

 

Avoid using eval unnecessarily. eval() is a dangerous function, and the code it executes has the rights of the executor. If the string code you run with eval() is manipulated and modified by a malicious party (someone with bad intentions), you may end up running malicious code on the user’s computer with the permissions of your page/extension.

It will execute JS code and has XSS vulnerability.

If you just want to remember this method, you have to verify the json parameter.

 var rx_One= /^[\],:{}\s]*$/;
 var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
 var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(&#  63;:[eE][+\-]?\d+)?/g;
 var rx_four = /(?:^|:|,)(?:\s*\[)+/g;
 if (
  rx_one.test(
   json
    .replace(rx_two, "@")
    .replace(rx_three, "]")
    .replace(rx_four, "")
  )
 ) {
  var obj = eval("(" +json + ")");
 }

 

3.2 The second type: Function

Source of the magical eval() and new Function()

Core: Function and eval have the same string parameter characteristics.

 var func = new Function(arg1, arg2, ..., functionBody);

In practical applications of converting JSON, this is all that is needed.

 var jsOnStr= '{ "age": 20, "name": "jack" }'
 var json = (new Function('return ' + jsonStr))();

Eval and Function both have the function of dynamically compiling js code, but their use is not recommended in actual programming.

This is interview-oriented programming, writing these two is enough. As for the third and fourth types, they involve cumbersome recursion and state machine-related principles. For details, see:

“Three Implementation Methods of JSON.parse”

4. Implement a call or apply

Source of implementation adaptation: Javascript in-depth simulation implementation of call and apply #11

call syntax:

fun.call(thisArg, arg1, arg2, …), calls a function, which has a �(that.status === REJECTED) { // Failure status
return newPromise = new Promise((resolve, reject) => {
setTimeout(() => {
try {
let x = onRejected(that.reason);
resolvePromise(newPromise, x, resolve, reject);
} catch(e) {
reject(e);
}
});
});
}

if (that.status === PENDING) { // Waiting state
// When resolve/rejected is called asynchronously, the onFulfilled/onRejected collection is temporarily stored in the collection.
return newPromise = new Promise((resolve, reject) => {
that.onFulfilledCallbacks.push((value) => {
try {
let x = onFulfilled(value);
resolvePromise(newPromise, x, resolve, reject);
} catch(e) {
reject(e);
}
});
that.onRejectedCallbacks.push((reason) => {
try {
let x = onRejected(reason);
resolvePromise(newPromise, x, resolve, reject);
} catch(e) {
reject(e);
}
});
});
}
};

emmm, I’d better write back the advanced version obediently.

9. Debouncing and Throttling

The scroll event itself will trigger the re-rendering of the page, and the handler of the scroll event will be triggered frequently. Therefore, there should be no complex operations inside the event handler. For example, DOM operations should not be placed in event processing.
For such high-frequency triggering event problems (such as page scroll, screen resize, monitoring user input, etc.), there are two commonly used solutions, anti-shake and throttling.

9.1 Debouncing implementation

Typical example: Limit mouse combo triggers.
A better explanation is:

When an event occurs, the event processor has to wait for a certain threshold time. If no event occurs after this period of time, the last event that occurred will be processed. Assume that the specified time is reached within 0.01 seconds, and another event occurs. Then the previous wait is invalid, and you need to wait for the specified time again.

 // Anti-shake function
 function debounce(fn,wait=50,immediate) {
  let timer;
  return function() {
   if(immediate) {
    fn.apply(this,arguments)
   }
   if(timer) clearTimeout(timer)
   timer = setTimeout(()=> {
    fn.apply(this,arguments)
   },wait)
  }
 }
 

Combined example: rolling anti-shake

 //Simple anti-shake function
 //The handler that actually wants to be bound to the scroll event
 function realFunc(){
  console.log("Success");
 }

 // Use anti-shake
 window.addEventListener('scroll',debounce(realFunc,500));
 // No anti-shake is used
 window.addEventListener('scroll',realFunc);

 

9.2 Throttling implementation

It can be understood that events are transmitted in a pipeline. After adding this throttle valve, the flow rate of events will slow down. In fact, this is what this function does. It can limit the calling frequency of a function to a certain threshold, such as 1s, then this function will definitely not be called twice within 1s

Simple throttling function:

 function throttle(fn, wait) {
 let prev = new Date();
 return function() {
 const args = arguments;
 const now = new Date();
 if (now - prev > wait) {
 fn.apply(this, args);
 prev = new Date();
 }
 }

 

9.3 Combining practice

Switch the mode through the third parameter.

 const throttle = function(fn, delay, isDebounce) {
  let timer
  let lastCall = 0
  return function (...args) {
  if (isDebounce) {
   if (timer) clearTimeout(timer)
   timer = setTimeout(() => {
   fn(...args)
   }, delay)
  } else {
   const now = new Date().getTime()
   if (now - lastCall <delay) return
   lastCall = now
   fn(...args)
  }
  }
 }

 

10. Handwrite a JS deep copy

There is the most famous beggar version implementation, which is also mentioned in “Javascript You Don’t Know (Part 1)”:

10.1 Beggars Edition

  var newObj = JSON.parse( JSON.stringify( someObj ) );

10.2 Sufficient version for interviews

 function deepCopy(obj){
  //Determine whether it is a simple data type,
  if(typeof obj == "object"){
   //Complex data type
   var result = obj.cOnstructor== Array ? [] : {};
   for(let i in obj){
    result[i] = typeof obj[i] == "object" ? deepCopy(obj[i]) : obj[i];
   }
  }else {
   //Simple data type direct == assignment
   var result = obj;
  }
  return result;
 }

 

There are discussions about deep copying every day, so I will post two types here, after all, I…

11. Implement an instanceOf

 function instanceOf(left,right) {

  let proto = left.__proto__;
  let prototype = right.prototype
  while(true) {
   if(proto === null) return false
   if(proto === prototype) return true
   proto = proto.__proto__;
  }
 }

 

The above is the detailed explanation and integration of Javascript handwritten code introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support of the website!

{
if(proto === null) return false
if(proto === prototype) return true
proto = proto.__proto__;
}
}

The above is the detailed explanation and integration of Javascript handwritten code introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support of the website!

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/697283

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索