繼承
es6:
class People {
constructor(name) {
this.name = name;
}
}
class Man extends People{
constructor(name) {
super(name)
}
}
let man = new Man('admin')
寄生組合繼承:
function People(name) {
this.name = name
}
function Man(name){
People.call(this,name)
}
(function(){
let Super = {}
Super.prototype = People.prototype;
Man.prototype = new Super()
})()
Man.prototype.constructor = Man;
new
? 創(chuàng)建一個空對象淘衙,將它的引用賦給 this劫侧,繼承函數(shù)的原型柿祈。
? 通過 this 將屬性和方法添加至這個對象
? 最后返回 this 指向的新對象丑婿,也就是實例(如果沒有手動返回其他的對象)
function People(name) {
this.name = name
}
People.prototype.say = function() {
console.log(this.name);
}
function _new(constructor, ...args) {
let temp = Object.create(constructor.prototype);
let instance = constructor.apply(temp, args);
return Object.prototype.toString.call(instance) === '[object object]' ? instance : temp;
}
深拷貝
通過JSON對象實現(xiàn)深拷貝 :
let deepData = JSON.parse(JSON.stringify(data))
通過Object.assign()拷貝(淺拷貝)
let deepData = Object.assign({},data)
遞歸實現(xiàn)
function deepClone(obj){
let objClone = Array.isArray(obj) ? [] : {};
if (obj && typeof obj === 'object') {
for(let key in obj){
if (obj[key] && typeof obj[key] === 'object'){
objClone[key] = deepClone(obj[key]);
}else{
objClone[key] = obj[key]
}
}
}
return objClone;
}
數(shù)組去重
ES6set去重
function uniq(arr){
var a=new Set(arr);
var b=[...a];
return b
}
function uniq(arr){
var temp = []; //一個新的臨時數(shù)組
for(var i = 0; i < array.length; i++){
if(temp.indexOf(arr[i]) == -1){ //建議用includes(ES6)
temp.push(arr[i]);
}
}
return temp;
}
防抖
防抖在指定時間間隔里再次調(diào)用函數(shù)究西,會清除定時器帝嗡,重新計時绸栅,直到在最新的計時時間間隔里沒有調(diào)用函數(shù)螺男,才會執(zhí)行定時器里的函數(shù)
function debounce(fn,delay){
var timer
return function(...args){
if(timer){
clearTimeout(timer)
}
timer = setTimeout(()=>{
fn.apply(this,args)
}, delay)
}
}
節(jié)流
指定時間間隔后會執(zhí)行一次函數(shù)洛勉,不會清除定時器而重新計時
function throttle(fn,delay){
let timer
let flag = true
return function(...args){
if(!flag){
return
}
flag = false
timer = setTimeout(()=>{
fn.apply(this,args)
flag = true
},delay)
}
}
sleep
const sleep = time => {
return new Promise(resolve => setTimeout(resolve,time)
) }