Know your enemy and win every battle. The interview is the same, want to get the offer of large factory, first of all we have to understand their interview routine, today small cicadas prepared ten front-end necessary high-frequency interview questions, I hope to help you ~
1. Write an observer pattern
class Subject{
constructor(name){
this.name = name
this.observers = []
this.state = ‘XXXX’
}
// The observed provides a way to receive the observer
attach(observer){
this.observers.push(observer)
}
// Change the state of the observed
setState(newState){
this.state = newState
this.observers.forEach(o=>{
o.update(newState)
})
}
}
class Observer{
constructor(name){
this.name = name
}
update(newState){
console.log(`
{newState}`)
}
}
// The observed light
Let sub = new Subject(‘ light ‘)
Let mm = new Observer(‘ xiaoming ‘)
Let jj = new Observer(‘ xiaojian ‘)
// Subscribe to observer
sub.attach(mm)
sub.attach(jj)
Sub.setstate (‘ The light is on ‘)
2. EventEmitter implementation
class EventEmitter {
constructor() {
this.events = {};
}
on(event, callback) {
let callbacks = this.events[event] || [];
callbacks.push(callback);
this.events[event] = callbacks;
return this;
}
off(event, callback) {
let callbacks = this.events[event];
this.events[event] = callbacks && callbacks.filter(fn => fn ! == callback);
return this;
}
emit(event, … args) {
let callbacks = this.events[event];
callbacks.forEach(fn => {
fn(… args);
});
return this;
}
once(event, callback) {
let wrapFun = function (… args) {
callback(… args);
this.off(event, wrapFun);
};
this.on(event, wrapFun);
return this;
}
}
3. Write a generic event listener function.
const EventUtils = {
/ / sight, respectively dom0 | | dom2 | | IE way to bind the event
// Add events
addEvent: function(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else if (element.attachEvent) {
element.attachEvent(“on” + type, handler);
} else {
element[“on” + type] = handler;
}
},
// Remove the event
removeEvent: function(element, type, handler) {
if (element.removeEventListener) {
element.removeEventListener(type, handler, false);
} else if (element.detachEvent) {
element.detachEvent(“on” + type, handler);
} else {
element[“on” + type] = null;
}
},
// Get the event target
getTarget: function(event) {
return event.target || event.srcElement;
},
// Get a reference to the event object, get all the information about the event, and ensure that the event is always available
getEvent: function(event) {
return event || window.event;
},
// Prevent events (mainly event bubbling, since IE does not support event capture)
stopPropagation: function(event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
// Cancel the default behavior of the event
preventDefault: function(event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
};
4. How to implement a sleep
The sleep function puts a thread to sleep and then wakes it up at a specified time.
function sleep(delay) {
var start = (new Date()).getTime();
while ((new Date()).getTime() – start < delay) {
continue;
}
}
function test() {
console.log(‘111’);
sleep(2000);
console.log(‘222’);
}
test()
5. Implement Object. Assign
Object.assign2 = function(target, … source) {
if (target == null) {
throw new TypeError(‘Cannot convert undefined or null to object’)
}
let ret = Object(target)
source.forEach(function(obj) {
if (obj ! = null) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
ret[key] = obj[key]
}
}
}
})
return ret
}
6. Instanceof implementation
Instanceof is an instanceof B used to determine whether A is an instanceof b. the expression A instanceof B returns true if A is an instanceof B, false otherwise.
The instanceof operator tests whether an object has a constructor’s Prototype property in its prototype chain.
Cannot detect basic data types, results on the prototype chain may not be accurate, cannot detect NULL,undefined
Implementation: Iterate through the left variable’s prototype chain until the right variable’s prototype is found. If not, return false
function myInstanceOf(a,b){
let left = a.__proto__;
let right = b.prototype;
while(true){
if(left == null){
return false
}
if(left == right){
return true
}
left = left.__proto__
}
}
// The instanceof operator is used to determine whether the constructor’s prototype property appears anywhere in the object’s prototype chain.
function myInstanceof(left, right) {
Let proto = object.getProtoTypeof (left), // Get the prototype of the Object
prototype = right.prototype; // Get the constructor’s prototype object
// Check whether the constructor’s prototype object is on the prototype chain
while (true) {
if (! proto) return false;
if (proto === prototype) return true;
proto = Object.getPrototypeOf(proto);
}
}
7. Implement debounce function
Continuous trigger in last execution method, scenario: input box match
let debounce = (fn,time = 1000) => {
let timeLock = null
return function (… args){
clearTimeout(timeLock)
timeLock = setTimeout(()=>{
fn(… args)
},time)
}
}
8. Implement throttle functions
Trigger only once in a certain period of time, scenario: long list scrolling throttling
let throttle = (fn,time = 1000) => {
let flag = true;
return function (… args){
if(flag){
flag = false;
setTimeout(()=>{
flag = true;
fn(… args)
},time)
}
}
}
9. Deepclone
Determine the type, re, and date to return the new object directly
An empty or non-object type that returns the original value
Consider circular references and determine if the hash contains a value that returns directly from the hash
Add a corresponding new obj.constructor to the hash
Traversal object recursion (regular keys and keys are symbol cases)
function deepClone(obj,hash = new WeakMap()){
if(obj instanceof RegExp) return new RegExp(obj);
if(obj instanceof Date) return new Date(obj);
if(obj === null || typeof obj ! == ‘object’) return obj;
// Loop references
if(hash.has(obj)){
return hash.get(obj)
}
// New a corresponding object
//obj为Array,相当于new Array()
//obj = Object, equivalent to new Object()
let constr = new obj.constructor();
hash.set(obj,constr);
for(let key in obj){
if(obj.hasOwnProperty(key)){
constr[key] = deepClone(obj[key],hash)
}
}
// Consider the case of symbol
let symbolObj = Object.getOwnPropertySymbols(obj)
for(let i=0; i<symbolObj.length; i++){
if(obj.hasOwnProperty(symbolObj[i])){
constr[symbolObj[i]] = deepClone(obj[symbolObj[i]],hash)
}
}
return constr
}
10. ES6 inheritance
//class is equivalent to the es5 constructor
// When defining a method in a class, do not add function before or after it
// All methods defined in class are not enumerable
// Class can only define methods, not objects, variables, etc
// Strict mode is the default in both class and method
//es5 uses constructor as an implicit attribute
class People{
constructor(name=’wang’,age=’27’){
this.name = name;
this.age = age;
}
eat(){
console.log(`
{this.age} eat food`)
}
}
// Inherits the parent class
class Woman extends People{
constructor(name = ‘ren’,age = ’27’){
// Inherits the superclass attributes
super(name, age);
}
eat(){
// Inherits the parent method
super.eat()
}
}
let wonmanObj=new Woman(‘xiaoxiami’);
wonmanObj.eat();
// ES5 inherits the instance object of the subclass and then adds the methods of the Parent class to this (parent.apply (this)).
// Es6 inheritance uses the keyword super to create an instance object of the parent class, this, and then modify this in the subclass class.