文章目录
面试题整理
1. 闭包的使用场景
1.1 闭包实际场景应用—函数防抖
比如要缩放窗口 触发onresize 事件 需要在这时候做一件事情,但是我们希望拖动的时候只触发一次,
window.onresize = debounce(fn,500)
function debounce(fn){
var timer = null
return function(){
if(timer){ //timer第一次执行后会保存在内存里 永远都是执行器 直到最后被触发
clearTimeout(timer)
timer = null
}
timer = setTimeout(function(){
fn()
},1000)
}
}
var fn = function(){
console.log('fn')
}
1.2 闭包实际场景应用—单例模式
class CreateUser {
constructor(name) {
this.name = name;
this.getName();
}
getName() {
return this.name;
}
}
// 代理实现单例模式
var ProxyMode = (function() {
var instance = null;
return function(name) {
if(!instance) {
instance = new CreateUser(name);
}
return instance;
}
})();
// 测试单体模式的实例
var a = ProxyMode("aaa");
var b = ProxyMode("bbb");
// 因为单体模式是只实例化一次,所以下面的实例是相等的
console.log(a === b); //true
1.3 闭包实际场景应用—单例模式
class CreateUser {
constructor(name) {
this.name = name;
this.getName();
}
getName() {
return this.name;
}
}
// 代理实现单例模式
var ProxyMode = (function() {
var instance = null;
return function(name) {
if(!instance) {
instance = new CreateUser(name);
}
return instance;
}
})();
// 测试单体模式的实例
var a = ProxyMode("aaa");
var b = ProxyMode("bbb");
// 因为单体模式是只实例化一次,所以下面的实例是相等的
console.log(a === b); //true
1.4 setTimeout输出正确的值
for(var i=0;i<10;i++){
((j)=>{
setTimeout(function(){
console.log(j)//1-10
},1000)})(i)
}
2. Promise中使用try。。。catch能否捕获异常
3. 原型的继承
4. var p1 = new Person()都发生了什么?
1.var p1 = new Object(); //此时p1._proto_ = Object Prototype
2.p1._proto_ = Person.prototype;
3.Person.call(p1);//使用新对象p1调用函数Person,将this作用域给p1