继承
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
• 创建一个空对象,将它的引用赋给 this,继承函数的原型。
• 通过 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对象实现深拷贝 :
let deepData = JSON.parse(JSON.stringify(data))
通过Object.assign()拷贝(浅拷贝)
let deepData = Object.assign({},data)
递归实现
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;
}
数组去重
ES6set去重
function uniq(arr){
var a=new Set(arr);
var b=[...a];
return b
}
function uniq(arr){
var temp = []; //一个新的临时数组
for(var i = 0; i < array.length; i++){
if(temp.indexOf(arr[i]) == -1){ //建议用includes(ES6)
temp.push(arr[i]);
}
}
return temp;
}
防抖
防抖在指定时间间隔里再次调用函数,会清除定时器,重新计时,直到在最新的计时时间间隔里没有调用函数,才会执行定时器里的函数
function debounce(fn,delay){
var timer
return function(...args){
if(timer){
clearTimeout(timer)
}
timer = setTimeout(()=>{
fn.apply(this,args)
}, delay)
}
}
节流
指定时间间隔后会执行一次函数,不会清除定时器而重新计时
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)
) }