Autumn recruitment has gradually begun, combined with the masters of the handwritten questions on the common topics to do sorting, review with.
The event agent
ul.addEventListener('click'.function(e){
console.log(e,e.target)
if(e.target&&e.target.tagName.toLowerCase()=='li') {console.log('print')}})Copy the code
If the throttle
[flag=false] // Throttling is only triggered once within a unit.
function throttle(fn,delay){
let flag = true;
let timer = null;
return function(. args){
let context = this
if(! flag)return
flag = false
clearTimeout(timer)
timer = setTimeout(function(){
fn.apply(context,args)
flag = true
},delay)
}
}
[clearTimeout(timer)] [clearTimeout(timer)]
function debounce(fn, delay){
let timer = null;
return function(. args){
let context = this
if(timer) clearTimeout(timer)
timer = setTimeout(function(){
fn.apply(context,args)
},delay)
}
}
Copy the code
Array to heavy
/ / 1. Set method
let arr1 = array= >[...new Set(array)]
// 2.filter
function arr2(array){
var res = array.filter(function(item,index,array){
return array.indexOf(item)===index;
})
return res
}
// 3. Object key value pairs
function arr3(array){
var obj = {}
return array.filter(function(item,index,array){
return obj.hasOwnProperty(typeof item + item)?false:(obj[typeof item+item]=true)})}Copy the code
The function is currified
function sum(. args1){
return function(. args2){
return [...args1,...args2].reduce((p,n) = >p+n)
}
}
Copy the code
An array of flat
let flatDeep = (arr) = >{
return arr.reduce((res,cur) = >{
if(Array.isArray(cur)){
return [...res,...flatDeep(cur)]
}else{
return [...res,cur]
}
},[])
}
function flatten(arr) {
let result=[]
for (let i=0,len=arr.length; i<len; i++) {if (Array.isArray(arr[i])) {
result=result.concat(flatten(arr[i]))
} else {
result.push(arr[i])
}
}
return result
}
Copy the code
copy
/ / shallow copyobj1 = {... obj}Object.assign({},obj)
function copy(obj){
let copyobj = {}
for(let key in obj){
copyobj[key] = obj[key]
}
return copyobj
}
/ / copy
function deepcopy(obj,map = new WeakMap(a)){
if(obj instanceof RegExp) return new RegExp(obj);
if(obj instanceof Date) return new Date(obj);
if(typeof obj ==='object') {let copyobj = Array.isArray(obj)? [] : {};if(map.get(obj)){
return map.get(obj)
}
map.set(obj,copyobj)
for(let key in obj){
copyobj[key] = deepcopy(obj[key],map);
}
return copyobj
}else{
return obj
}
}
Copy the code
Write call, apply, and bind by hand
// call
Function.prototype.maCall = function(){
let [context,...args] = [...arguments]
context = Object(context)||window
let fn = Symbol(a); context[fn] =this
letres = context[fn](... args)delete context[fn]
return res
}
/ / the apply handwriting
Function.prototype.myApply = function(){
let [context,args] = [...arguments]
context = Object(context)||window
let fn = Symbol()
context[fn] = this
letres = context[fn](... args)delete context[fn]
return res
}
/ / handwritten bind
Function.prototype.bind = function(context,... args){
return (. newArgs) = >{
return this.call(context,... args,... newArgs) } }Copy the code
Implement the new operation
function _new(){
let obj = {};
let [constructor.args] = [...arguments]
obj._proto_ = constructor.prototype
let res = constructor.apply(obj,args)
return res instanceof Object?res:obj;
}
Copy the code
Implement instanceof
function myInstaceof(son,father){
while(true){
son = son._proto_;
if(! son)return false;
if(son = father.prototype) return true}}Copy the code
Remove the blank space
function myTrim(str){
return str.replace(/(^\s+)|(^\s+$)/g.' ')}Copy the code
Handwritten reduce
Array.prototype.myReduce = function(fn, initVal){
let result = initVal;
let i = 0;
if(typeof initVal == 'undefined'){
result = this[i]
i++;
}
while(i<this.length){
result = fn(result,this[i])
}
return result
}
Copy the code
inheritance
Prototype chain inheritance
function Father(){
this.color = []
}
Father.prototype.getColor = function(){
console.log(this.color)
}
function Son(){
this.name =this.name
}
Son.prototype = new Father()
Copy the code
The constructor
function Father(){}function Son(){
Father.call(this)}var res = new Son()
Copy the code
Combination of inheritance
function Father(name){
this.name = name;
this.color = [];
}
Father.prototype.getName = function(){
console.log()
}
function Son(){
Father.call(this)
}
Son.prototype = new Father();
Son.prototyp.constructor = Son
Copy the code
Primary inheritance
function object(obj){
function F(){}
F.prototype = obj;
return new F()
}
Object.create()
Copy the code
Parasitic inheritance
function createAnother(original){
var clone = Object.create(original);
clone.sayHi = function(){
alert('hi')}return clone
}
Copy the code
Parasitic combinatorial inheritance
Copy the code
The Class inheritance
Class Father{
constructor(name){
this.name = name
}
getName(){
return this.name
}
}
Class Son extends Father{
constructor(name.age){
super(name)
this.age = age
}
}
Copy the code
AJAX
const getJSON = function(url){
return new Promise((resolve,reject) = >{
const xhr = new XMLHttpRequest;
xhr.open('get',url,true)
xhr.setRequestHeader('Accept'.'application/json')
xhr.onreadystatechange = function(){
if(xhr.readyState! = =4) return
if(xhr.status === 200||xhr.status ===304){
resolve(xhr.responseText)
}else{
reject(new Error(xhr.responseText))
}
}
xhr.send()
})
}
Copy the code
Write a Promise
const PENDING = 'PENDING';
const FULFILLED = 'FULFILLED';
const REJECTED = 'REJECTED';
class Promise {
constructor(executor) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
// Store the successful callback
this.onResolvedCallbacks = [];
// Store the failed callback
this.onRejectedCallbacks= [];
let resolve = (value) = > {
if(this.status === PENDING) {
this.status = FULFILLED;
this.value = value;
// Execute the corresponding functions in turn
this.onResolvedCallbacks.forEach(fn= >fn()); }}let reject = (reason) = > {
if(this.status === PENDING) {
this.status = REJECTED;
this.reason = reason;
// Execute the corresponding functions in turn
this.onRejectedCallbacks.forEach(fn= >fn()); }}try {
executor(resolve,reject)
} catch (error) {
reject(error)
}
}
then(onFulfilled, onRejected) {
if (this.status === FULFILLED) {
onFulfilled(this.value)
}
if (this.status === REJECTED) {
onRejected(this.reason)
}
if (this.status === PENDING) {
// If the promise state is pending, the onFulfilled and onRejected functions need to be stored. After the state is determined, the corresponding functions will be executed successively
this.onResolvedCallbacks.push(() = > {
onFulfilled(this.value)
});
// If the promise state is pending, the onFulfilled and onRejected functions need to be stored. After the state is determined, the corresponding functions will be executed successively
this.onRejectedCallbacks.push(() = > {
onRejected(this.reason); })}}}Copy the code
Promise.all
Promise.myAll = function(promiseArr){
return new Promise((resolve,reject) = >{
const ans = [];
let index = 0;
for(let i = 0; i<promiseArr.length; i++){ promiseArr[i].then(res= >{
ans[i] = res;
index++;
if(index==promiseArr.length){
resolve(ans);
}
})
.catch(err= >reject(err))
}
})
}
Copy the code
Promise.race
Promise.race = function(promiseArr){
return new Promise((resolve,reject) = >{
promiseArr.forEach(p= >{
promiseArr.resolve(p).then(
val= >resolve(val),
err= >{reject(err)
})
})
})
}
Copy the code
Publish and subscribe model
class EventEmitter{
constructor(){
this.events = {}
}
on(eventName,callback){
if(!this.events[eventName]){
this.events[eventName] = [callback]
}else{
this.events[eventName].push(callback)
}
}
emit(eventName,... rest){
if(this.events[eventName]){
this.events[eventName].forEach( item= >{
item.apply(this,rest)
})
}else{
console.log('error')}}remove(eventName,callback){
if(this.events[eventName]){
this.events[eventName] = this.events[eventName].filter( item= >item ! == callback) } }once(eventName,callback){
function one(){
callback.apply(this.arguments);
this.remove(eventName,one)
}
this.one(eventName,callback)
}
}
Copy the code