Js拾忆
instanceof运算符:他是判断一个构造函数的prototype是否在对象的原型链上查找到
var a = new Array();
console.log(a instanceof Array) //true
//a.__proto__ == Array.prototype
//如果a不是对象将返回false
//如果右边不是构造函数将报错
箭头函数注意点,当箭头函数返回一个对象的话,要使用大括号把对象括起来,要不然会被认为是一个函数体
var fn = () => ({a:10});
Object.assign(target,obj1,obj2...):合并对象,将源对象的所有可枚举属性复制到目标对象,属于浅拷贝
函数操作:
fn1();//fn1
fn2();//报错,因为js代码执行过程会先函数声明预解析
//1.函数声明
function fn1(){
console.log('fn1');
}
//2.函数表达式
var fn2 = function(){
console.log('fn2');
}
//3.new Function();这个方式创建函数会先解析字符串为js的代码,执行速度慢,也是函数对象
var fn3 = new Function('var name = "小明";console.log(name);');
fn3(); //小明
//------------------------------------------
if(true){
function fn1(){
console.log('fn1');
}
}else{
function fn1(){
console.log('fn2');
}
}
fn1();//fn1,在现代浏览器里if语句里的函数声明不会预解析,老版本IE会解析
/*调用函数的方式
1、普通函数调用 this指向window
2、对象里的方法调用 this指向调用改方法的对象
3、作为构造函数调用 this指向由该构造函数创建的对象
4、作为事件的处理函数 this触发该事件的对象
5、作为定时器的参数 this指向window
*/
浅拷贝、深拷贝:
//浅拷贝,把一个对象复制给另外一个对象的时候,只能复制基本类型数据,如果这个对象还有引用类型的时候就不会复制该对象里面里面的成员
obj1 = {
name : '小明',
age : 16
}
obj2 = {};
for(var attr in obj1){
obj2[attr] = obj1[attr];
}
//深拷贝
function deepCoop(obj1,obj2){
var obj2 = obj2 || {};
for(var attr in obj1){
if(typeof obj1[attr] == 'object'){
obj2[attr] = (obj1[attr].constructor === Array) ? [] : {};
deepCoop(obj1[attr],obj2[attr])
}else{
obj2[attr] = obj1[attr];
}
}
return obj2;
}
函数节流与函数防抖:
//节流和防抖是为了优化高频率执行js的方法
//节流是多次执行方法的时候,让该方法在规定的时间内执行一次,有俩种方法
//1.时间戳版
let throttle = function(fn,delay){
let oldTime = Date.now();
return function(){
let that = this;
let args = arguments;
let newTime = Date.now();
if(newTime - oldTime >= delay){
fn.apply(that,args);
oldTime = Date.now();
}
}
}
//2.定时器版
let throttle = function(fn,delay){
let timer = null
return function(){
let that = this;
let args = arguments;
if(!timer){
timer = setTimeout(function(){
fn.apply(that,args);
timer = null;
},delay);
}
}
}
//防抖是多次执行js方法的时候,等一段时间没有执行这方法的时候执行一次
let debounce = function(fn,delay){
let timer = null
return function(){
let that = this;
let args = arguments;
if(timer !== null){
clearTimeout(timer);
}
timer = setTimeout(function(){
fn.apply(that,args);
},delay)
}
}