博主准备了几周的字节前端面试,刷了一波知识点详解,还有网上的面经和面试题。在准备面试中,我发现按照知识点类型(JS/网络/Vue/CSS等)深入理解,和牢记一些常问面试题,是非常有帮助的。
下面按知识点类型和每个类型里的常见程度(1-5)总结了几十道热门前端面试题,每种程度中的问题按个人认为的难度排序。4-5为必须了解的核心概念题,2-3为细节概念题和代码题,1为偏门的特殊概念和个例题。
JavaScript
5
简述var,let,const的区别
- 只有var有变量提升
- let和const是块级作用域,不能跨块访问
- let和const不允许重复声明
- 如果在let和const被赋值前调用会报错,var不会
- const值不能被改变
使用new关键词发生了什么
- 创建一个新对象
- 将新对象的_proto_指向构造函数的prototype对象
- 将构造函数的作用域赋值给新对象(this指向新对象)
- 执行构造函数中的代码(给新对象添加属性)
- 返回新对象
this是如何确定指向对象的?
- 判断函数类型:箭头函数则是包含箭头函数的第一个普通函数中的this,bind/call/apply则是第一个参数,普通函数见下一步
- 判断调用方式:new则将this指向创建对象,直接调用则判断是否为对象中的方法(foo()则this为window,obj()则this为obj)
实现对象继承的几种方法
- 原型链
利用原型让子类型继承父类型的属性和方法,即让子类型的原型对象等于父类型的构造函数的实例
缺点:无法传递参数到父类型的构造函数中
function SuperType(){
this.property = true;
}
SuperType.prototype.getSuperValue = function(){
return this.property;
};
function SubType(){
this.subproperty = false;
}
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function(){
return this.subproperty;
};
var instance = new SubType();
alert(instance.getSuperValue()); \\true
- 借用构造函数
通过apply()和call(),在子类型的构造函数的内部调用父类型的构造函数,绑定在自身this上
缺点:无法复用父类的函数
function Supertype(name){
this.name = name;
}
function Subtype(){
Supertype.call(this,'Annika');
this.age = 21;
}
var instance = new Subtype;
console.log(instance.name); \\Annika
console.log(instance.age); \\29
- 组合继承
合并原型链和借用构造函数方法:用原型链实现对原型属性和方法的继承,用借用构造函数模式实现对实例属性的继承
缺点:生成了两份父类的实例,如果删除子类实例上的属性,调用还能获取到原型链上的。
function Supertype(name){
this.name = name;
this.colors = ["red","green","blue"];
}
Supertype.prototype.sayName = function(){
console.log(this.name);
};
function Subtype(name, age){
\\借用构造函数 继承属性
Supertype.call(this, name);
this.age = age;
}
\\原型链 继承方法
Subtype.prototype = new Supertype();
Subtype.prototype.constructor = Subtype;
Subtype.prototype.sayAge = function(){
console.log(this.age);
};
let instance = new Subtype('Annika',21);
instance.colors.push("black");
\\["red", "green", "blue", "black"]
console.log(instance1.colors);
instance.sayName(); \\Annika
instance.sayAge(); \\21
- 寄生组合继承
相对于组合继承,避免new父类构造函数的实例。
function Supertype(name){
this.name = name;
this.colors = ["red","green","blue"];
}
Supertype.prototype.sayName = function(){
console.log(this.name);
};
function Subtype(name, age){
Supertype.call(this, name);
this.age = age;
}
\\不执行父类构造函数,返回父类的原型对象
Subtype.prototype = Object.create(Supertype.prototype);
Subtype.prototype.constructor = Subtype;
Subtype.prototype.sayAge = function(){
console.log(this.age);
};
let instance = new Subtype(