这是我参与8月更文挑战的第7天,活动详情查看:8月更文挑战
复习一下上一篇文章的一些代码
- 防抖:
最后一次触发事件N秒内未重新触发才执行程序,否则重新计时 - 节流:
N秒内仅触发一次事件 - 简单判断类型:
typeof无法正常判断null且引用类型仅能正确判断Function,instancof仅能正常判断引用类型,最佳方法:Object.prototype.toString.call(arg) - 浅拷贝:完整拷贝某个对象的所有属性,对于拷贝后的基础数据类型,不会因为被拷贝对象属性的修改而受影响,而对于拷贝后的引用数据类型,会因为被拷贝对象属性的修改而受影响
- 深拷贝:完整拷贝某个对象的所有属性,对于拷贝后的引用数据类型,会开辟一个新的内存空间用于存储,因此不会因为拷贝对象属性的修改而受到影响
//防抖
function debounce(func,wait){
let timer = null;
return function(){
if(!timer) clearTimeout(timer);
timer = setTimeout(()=>{
func.call(this,arguments)
},wait)
}
}
//节流
function throttle(func,delay){
let canRun = true
return function(){
if(!canRun) return;
canRun = false;
setTimeout(()=>{
func.call(this,arguments);
canRun = true;
},delay)
}
}
//节流新
function throttle(func,wait){
let pre = 0;
return function(){
let now = Date.now();
if(now-pre>wait){
func.call(this,arguments)
pre = now;
}
}
}
//简单判断类型
function getType(arg){
return Object.prototype.toString.call(arg).slice(8,-1).toLowerCase();
}
/*
拷贝
*/
var person = {
"name":"tony",
"age":21,
"tech":{
"react":false
}
}
//浅拷贝
let personCopy1 = Object.assign({},person) //Object.assign方法
let personCopy2 = {...person} //ES6展开法
//深拷贝
let personCopy3 = JSON.parse(JSON.stringify(person)) //JSON.parse(JSON.stringify(obj))方法
//递归深拷贝法
function deepClone(obj){
if(typeof(obj) !== 'object') return;
var newObj = obj instanceof Array ? []:{};
for(var key in obj){
if(obj.hasOwnProperty(key)){
newObj[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key];
}
}
return newObj;
}
第二篇内容
1.继承
常用的两个继承方式:
- 组合继承(原型链继承+构造函数继承)
- 寄生式组合继承(组合继承的改进,)
/*
方法一:组合继承
*/
function Parent(age){
this.age = age;
}
Parent.prototype.sayAge = function(){
console.log(this.age);
}
//构造函数盗用,设置变量
function Child(age){
Parent.call(this,age)
}
//修改原型,继承方法
Child.prototype = new Parent();
////////////////////////////////////////////////////////////
/*
方法二:寄生式组合继承(组合继承的改进)
*/
function Parent(age){
this.age = age;
}
Parent.prototype.sayAge = function(){
console.log(this.age);
}
//构造函数盗用,设置变量
function Child(age){
Parent.call(this,age);
}
//原型链修改
const prototype = object(Parent.prototype);
prototype.constructor = Child;
Child.prototype = prototype;
2.数组去重
方法:
- ES5
filter - ES6
Set
//ES5 filter
function unique(arr){
var res = arr.filter(function(item,index,array){
return array.indexOf(item) === index
})
return res;
}
//ES6 Set
var unique = arr => [...new Set(arr)]
3.数组扁平化
数组扁平化:将多维数组拍平成一维数组
方法:
- 递归
- ES6 array.some
//ES5递归
function flattern(arr){
var array = [];
for(var i=0;i<arr.length;i++){
if(arr[i].isArray) array = array.concat( flattern(arr[i]) )
else array.push(arr[i])
}
return array
}
//ES6
function flatten(arr) {
while (arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}
4.new
步骤:
- 创建空对象
- 将对象原型进行指向
- 修改空对象上下文
- 返回空对象
function newFunc(Constructor,...args){
var obj = {}
obj.__proto__ = Constructor.prototype
Constructor.call(obj,args)
return obj
}