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
*/

 

 1 //浅拷贝,把一个对象复制给另外一个对象的时候,只能复制基本类型数据,如果这个对象还有引用类型的时候就不会复制该对象里面里面的成员
 2 
 3 obj1 = {
 4    name : '小明',
 5    age : 16    
 6 }
 7 
 8 obj2 = {};
 9 
10 for(var attr in obj1){
11      obj2[attr] = obj1[attr];
12 }
13 
14 //深拷贝
15 function deepCoop(obj1,obj2){
16     var obj2 = obj2 || {};
17     for(var attr in obj1){
18        if(typeof obj1[attr] == 'object'){
19            obj2[attr] = (obj1[attr].constructor === Array) ? [] : {};
20            deepCoop(obj1[attr],obj2[attr])
21        }else{
22           obj2[attr] = obj1[attr];
23        }
24     }
25     return obj2;
26 }
27         

 

posted @ 2018-12-27 10:30  cher。  阅读(133)  评论(0编辑  收藏  举报