前端常见面试题

2017-08-22  本文已影响0人  jia林

描述new一个对象的过程

function Fun(name,age){
  this.name = name;
  this.age = age;
  this.class = 'classname'
  //return this  这里是默认返回this
}
var f = new Fun('jialin',22)

原型继承案例--封装一个dom查询

function Elem(id){
  this.elem = document.getElementById(id)
}
Elem.prototype.html(val){
  var elem = this.elem;
  if(val){
   elem.innerHTML = val;
    return this;//返回一个对象,链式操作,利用jquery原理
 }else{
    return elem.innerHTML;
 }
}
Elem.prototype.on(type,fn){
    var elem = this.elem;
    elem.addEventListener(type,fn);
    return this;
}

var box = new Elem('inner');
box.html('this is test').on('click',function(){
      alert('this is update');
  }).html('<p>javascript</p>')

创建10个a,点击弹出对应的序号

for(var i = 0;i<10;i++){
  (function(i){
      var a = document.createElement("a");
        a.innerHTML = i + "<br>";
        a.addEventListener('click',function(e){
            e.preventDefault();//阻止默认事件
            alert(i);
        });
        document.body.appendChild(a)
  })(i)


}

封装变量,收敛权限

function isFirstLoad(){
   var _list =[];//以下划线命名一般表示私有变量 
  return function(id){
    if(_list.indexOf(id)>=0){
        return false
    }else{
          _list.push(id);
          return true;
    }
  }
}
var firstLoad = isFistLoad();
firstLoad(10);
firstLoad(10)
firstLoad(20)

获取当前年月日

function formatDate(time){
  if(!time){
    time = new Date();
  }
  var year = time.getFullYear();
  var month = time.getMonth() + 1;
  var date = time.getDate();
  if(month < 10){
     month = '0' + month;
    }
  if(date<10){
      date = '0' +date;
  }

  return year + '-' + month + '-' + date;
}
var time = new Date();
var formatDate = formatDate(time);
console.log( formatDate)

写一个能遍历对象和数组的函数

function forEach(obj,fn){
    var key;
    if(obj instanceof Array){
        obj.forEach(function(val,index){
            fn(index,val)
        });
    }else{
        for(key in obj){
            if(obj.hasOwnProperty(key)){
                fn(key)
            }
        }
    }
}

var arr = [1,2,3];
forEach(arr,function(index,val){
    console.log(index,val)
});
var a = {
    x:1,
    y:2
}
forEach(a ,function(index){
    console.log(index)
});

随机数截取

var random =Math.random();
random = random + '0000';
random = random.slice(1,4);
console.log(random)

完善通用绑定事件的函数

function bindEvent(elem,type,select,fn){
    if(fn == null){
        fn = select;
        select = null;
    }
    elem.addEventListener(type,function(e){
        var target;
        id(select){
            target = e.target;
            if(target.matches(select)){
                fn.call(target,e)
            }else{
                //不使用代理
                fn(e);
            }
        }
    })
}

合并DOM查询

var list = document.getElementById('box');
var frg = document.createDocumentFragment();
var x,li;
for(x = 0 ;x<10;x++){
    li = document.createElement('li');
    li.innerHTML = '1' + x;
    frg.appendChild(li)
}
list.appendChild(frg)
上一篇下一篇

猜你喜欢

热点阅读