前端面试题

132 阅读2分钟

一、继承

1. ES6 继承( 子类 extends 父类,子类 construct 中调用 super()即可 )
class Parent {
    constructor() {
        this.age = 18;
    }
}

class Child extends Parent {
    constructor() {
        super();
        this.name = "张三";
    }
}

const o1 = new Child();
console.log(o1.name, o1.age); // 张三 18
2. 原型链继承(子类的 prototype 指向父类的实例即可)
function Parent() {
    this.age = 18;
}

function Child() {
    this.name = "张三";
}

Child.prototype = new Parent(); // Child的prototype指向Parent的实例
const o1 = new Child();
console.log(o1.name, o1.age); // 张三 18
3. 借用构造函数(在子类中调用父类构造函数,并用 call 改变 this 指向指向子类)
function Parent() {
    this.age = 18;
}

function Child() {
    Parent.call(this); // 在子构造函数中调用父构造函数,并把this指向指向子类
    this.name = "张三";
}

const o1 = new Child();
console.log(o1.name, o1.age); // 张三 18
4. 组合式继承(原型链继承和借用构造函数两者结合)
function Parent() {
    this.age = 18;
}

function Child() {
    Parent.call(this); // 借用构造函数
    this.name = "张三";
}

Child.prototype = new Parent(); // 原型链
const o1 = new Child();
console.log(o1.name, o1.age); // 张三 18

二、localStorage、sessionStorage、Cookie 区别

共同点: 在客户端存储数据

不同点: 1. 数据存放有效期 2. 存储大小限制 3. 能否设置过期时间

// 1. 数据存放有效期
localStorage 始终有效【即使关闭浏览器或窗口也有效,也叫持久化存储】
sessionStorage 仅在当前浏览器窗口关闭前有效【关闭浏览器则消失】
Cookie 设置过期时间之前有效【即使关闭浏览器或窗口也有效】

// 2. 存储大小限制【注意:不同浏览器之间存储大小有所区别】
Cookie 大小限制 4k
localStorage、sessionStorage 不能超过5M

// 3. 能否设置过期时间
Cookie 可以设置过期时间
localStorage、sessionStorage 不可以设置过期时间

三、new 操作符原理(4 个步骤)

// new操作符
function create(fn, ...args) {
    // 1. 创建空对象
    const obj = {}; // const obj = Object.create({})
    // 2. 将空对象的原型,指向于构造函数的原型
    Object.setPrototypeOf(obj, fn.prototype);
    // 3. 将空对象作为构造函数的上下文(改变this指向)
    const result = fn.apply(obj, args);
    // 4. 对构造函数的返回值作处理(引用类型返回本身, 非引用类型返回创建的对象)
    return result instanceof Object ? result : obj;
}

function fun(name, age) {
    this.name = name;
    this.age = age;
    return {};
}

function fun2(name, age) {
    this.name = name;
    this.age = age;
    return 111;
}

console.log(create(fun, "tao", 10)); // {}
console.log(create(fun2, "tao", 10)); // fun { name: 'tao', age: 10 }

四、闭包

  1. 闭包是什么? 闭包是一个函数加上到创建函数的作用域的连接,闭包“关闭”了函数的自由变量
  2. 闭包可以解决什么问题【优点】
  • 内部函数可以访问到外部函数的局部变量
  • 解决的问题
var lis = document.getElementsByTagName("li");
for (var i = 0; i < lis.length; i++) {
    (function (a) {
        lis[a].onclick = function () {
            console.log(a);
        };
    })(i);
}
  1. 闭包的缺点
  • 变量会驻留在内存中,造成内存损耗问题【解决:把闭包的函数设置为null】
  • 内存泄漏【ie低版本浏览器会造成,高版本浏览器一般没有】