06_面试题_JS和ES6

0. 原型 & 原型链

image
image

function Person() {}
const p = new Person()

// 实例.__proto__ === 构造函数.prototype
console.log(p.__proto__ === Person.prototype) // true

// Person.prototype.constructor 指回构造函数
console.log(Person.prototype.constructor === Person) // true

// 所有普通对象原型终点:Object.prototype
console.log(Person.prototype.__proto__ === Object.prototype) // true
// Object.prototype.__proto__ 是 null,原型链到头
console.log(Object.prototype.__proto__) // null

原型继承和 Class 继承

image

1. ES5 原型继承一

缺点:父构造函数执行两次,原型上会多出一份不需要的实例属性

function Father(name) {
  this.name = name;
  this.arr = [1, 2, 3];
}

Father.prototype.say = function () {
  console.log(this.name);
};

// 定义子类
function Son(name, age) {
  Father.call(this, name); // 第一次父结构,实例属性
  this.age = age;
}
Son.prototype = new Father(); // 第二次父结构,原型上多一份实例属性
Son.prototype.constructor = Son; // 修复 constrctor

const s = new Son('小名', 20);
s.say();

2. ES5 原型继承二:寄生组合继承(推荐)

function Father(name) {
  this.name = name;
  this.arr = [1, 2, 3];
}

Father.prototype.say = function () {
  console.log(this.name);
  console.log('ss');
};

// 定义子类
function Son(name, age) {
  Father.call(this, name); // 第一次父结构,实例属性
  this.age = age;
}

// 重要核心代码:只继承父原型,不调用父的构造函数
Son.prototype = Object.create(Father.prototype);
Son.prototype.constructor = Son; // 修复 constrctor

const s = new Son('小名', 20);
s.say();

3. ES6 Class extends 继承

class Father {
  constructor(name) {
    this.name = name;
    this.arr = [1, 2, 3];
  }
  say() {
    console.log(this.name);
  }
  static hello() {
    console.log('static');
  }
}

// 子类
class Son extends Father {
  constructor(name, age) {
  // **调用父类构造函数**,创建 this
    super(name); // 必须第一行调用,调用父构造函数constructot,生成this
    this.age = age;
  }
  say() {
    super.say(); // 调用父类的say
    console.log(this.age);
  }
}

// 实例化
const s = new Son('小名', 20);
s.say();
Son.hello(); // 继承父类的静态方法

1. javascript的typeof返回的类型

image

typeof null → object
数组[]、普通对象{}都返回object,typeof 区分不开普通对象、数组、正则、日期

console.log(typeof undefined);    // 'undefined'
console.log(typeof true);         // 'boolean'
console.log(typeof 10);           // 'number'
console.log(typeof 'hi');         // 'string'
console.log(typeof Symbol());     // 'symbol'
console.log(typeof 10n);          // 'bigint'

console.log(typeof function(){}); // 'function'

console.log(typeof null);      // 'object'
console.log(typeof []);        // 'object'
console.log(typeof {});        // 'object'
console.log(typeof /reg/);        // 'object'
console.log(typeof new Date());        // 'object'

判断数组:Array.isArray(arr)
判断对象:

Object.prototype.toString.call(null)     // '[object Null]'
Object.prototype.toString.call([])      // '[object Array]'
Object.prototype.toString.call({})      // '[object Object]'
Object.prototype.toString.call(new Date()) // '[object Date]'
Object.prototype.toString.call(/abc/)    // '[object RegExp]'

2. 常见的强制类型转换和隐式类型转换

image

image

new Number/String/Boolean 是创建包装对象,一般不算类型转换

隐式类型转换:
image
image
image
image

3. split() 和 join() 的区别

split 是字符串方法,切割字符串得到数组;
join 是数组方法,拼接数组变成字符串

image
image

4. 数组常用方法

image
image
image
image
image

5. 事件绑定和普通事件有什么区别

click 只能绑定一个事件处理函数,会覆盖,只能冒泡触发;
addEventListener 可以绑定多个、支持捕获 / 冒泡控制、支持 once/passive,项目优先使用

image
image
image
image

6. DOM事件流、捕获、冒泡、委托

事件流分为捕获、目标、冒泡;
捕获是由外到内,冒泡由内向外;
事件委托借助冒泡,把事件绑在父级,统一处理子元素事件,适合动态列表

image
image
image
image
image
image
image

7. JS继承

父类统一示例:

function Person(name) {
  this.name = name;
}
Person.prototype.say = function () {
  console.log(this.name);
}

1. 原型链继承

function Student() {}

Student.prototype = new Person('张三');
// 修复constructor
Student.prototype.constructor = Student;

image

2. 借用构造函数(call 继承)

function Student(name) {
  Person.call(this, name);
}

image

3. 组合继承(原型链 + call,老式最常用)

function Student(name) {
  Person.call(this, name); // 第二次调用Person
}
Student.prototype = new Person(); // 第一次调用Person
Student.prototype.constructor = Student;

image

4. 原型式继承(Object.create)

const p = { name: 'xxx', say(){} };
const s = Object.create(p);

image

5. 寄生组合继承(最优 ES5 方案)

function Student(name) {
  Person.call(this, name);
}
// 核心:子类原型 = 父原型的副本,不new父构造
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

image

6. ES6 class extends(现在项目主流,语法糖)

class Person {
  constructor(name) {
    this.name = name;
  }
  say() {
    console.log(this.name);
  }
}
class Student extends Person {
  constructor(name) {
    super(name); // 必须调用super,等价父构造
  }
}

8. 闭包、作用域

8.1 作用域

image
image

8.2 闭包

函数 A 里面定义函数 B,B 可以访问 A 的变量,B 被拿到 A 外面执行,就形成闭包

内部函数引用外部函数作用域的变量,外部函数执行结束,作用域不会销毁
闭包就是能够读取其他函数内部变量的函数

image

function outer(){
  let count = 0;
  return function inner(){
    count++
    console.log(count)
  }
}
const fn = outer()
fn() //1
fn() //2

缺点:滥用闭包函数会造成内存泄露,因为闭包中引用到的包裹函数中定义的变量都永远不会被释放,所以我们应该在必要的时候,及时释放这个闭包函数

9. this指向

this 是谁,不看定义位置,看调用方式
箭头函数 this 继承外层

image
image
image
image
image

10. 如何阻止事件冒泡和默认事件

image
image

11. DOM 节点增删改方法

image

假设父节点 parent,新节点 newNode,参考节点 refNode
image
image
image
image

12. javascript 的本地对象,内置对象和宿主对象

image
image
image
image

13. document的ready和load的异同

// jQuery ready
$(document).ready(function(){})
// 简写
$(function(){})

// 原生 load
window.onload = function(){}

image
image

ready 是 jQuery 的,DOM 构建好就执行,不等图片;
load 是原生 window 事件,要等页面所有资源全部加载完毕才执行,执行更晚

document.onload:是在结构和样式加载完才执行 js
window.onload:不仅仅要在结构和样式加载完,还要执行完所有的样式、图片这些资源文件,全部加载完才会触发 window.onload 事件
Document.ready 原生中没有这个方法,jquery 中有 $().ready(function)

14. ==和===的不同

=== 先比类型,类型不同直接 false,无隐式转换;
== 类型不同会自动隐式转换后再比较
image

15. 常见跨域的解决方案

image

16. JS数据类型

image
image

17. 值类型和引用类型的区别

值类型存在栈,赋值复制数值,互不干扰;
引用类型栈存地址、数据放堆,赋值复制地址,修改会互相影响

image
image
image
image

18. BOM 浏览器对象模型

浏览器对象模型:用来和浏览器窗口交互

image
image
image
image

19. Javascript 创建对象的几种方式

19.1 字面量(最常用)

const obj1 = { name: '张三' }

19.2 new Object()

const obj2 = new Object()
obj2.name = '张三'

19.3 构造函数

function Person(name) {
  this.name = name
}
Person.prototype.say = function () {
  console.log(this.name)
}

const p2 = new Person('王五')

New做的事情

  • 创建一个空对象{}

  • 绑定this到这个新对象

  • 执行构造函数里面的回调

  • 默认返回这个新对象(如果return一个对象,就返回这个新对象)

19.4 Object.create(原型)

const proto = { say(){} }
const p3 = Object.create(proto)

19.5 ES6 class(语法糖,底层还是构造函数+原型)

class Person {
  constructor(name) {
    this.name = name
  }
  say() {
    console.log(this.name)
  }
}

const p4 = new Person('赵六')

20. iframe 的优缺点

优点:

  • 解决加载缓慢的第三方内容,如图标和广告等的加载问题

  • Security sandbox

  • 并行加载脚本

缺点:

  • iframe 会阻塞主页面的 Onload 事件

  • 即使内容为空,加载也需要时间

  • 没有语意

image
image
image

22. 如何防止表单的重复提交

避免用户多次点击提交按钮、网络慢重复发请求;前端只能辅助,后端校验是必须的
image
image
image

23. js 延迟加载的方式

目的是:不让 JS 阻塞 DOM 渲染,等合适时机再加载执行 js,提升首屏速度

默认 <script> 阻塞解析器,遇到就暂停 DOM 构建,下载 + 执行完才继续解析 HTML

image
image
image

image
image
image

24. documen.write 和 innerHTML 的区别

image

25. JS 内存泄漏常见场景

image
image
image
image
image
image

26. 判断一个字符串中出现次数最多的字符,统计这个次数

var str = 'asdfssaaasasasasaa';
function fn(str) {
  let newarr = {};
  Array.from(str).forEach((item) => {
    if (newarr[item]) {
      newarr[item] = newarr[item] + 1;
    } else {
      newarr[item] = 1;
    }
  });

  return newarr;
}

const m = fn(str);

// 计算最多出现的次数和相应的字符
let maxCount = 0;
let maxField = null;
for (let key in m) {
  if (m[key] >= maxCount) {
    maxCount = m[key];
    maxField = key;
  }
}
console.log(maxCount, maxField);

27. javascript 中的垃圾回收机制

核心是:找出不再被引用的对象,释放内存
常见:闭包、定时器不清、事件不解绑、DOM 节点删除后还保留引用
在 Javascript 中,如果一个对象不再被引用,那么这个对象就会被GC回收。如果两个对象互相引用,而不再 被第 3 者所引用,那么这两个互相引用的对象也会被回收。因为函数 a 被 b 引用,b 又被 a 外的 c 引用,这就是为什么函数a 执行后不会被回收的原因

28. 原生 js 实现 jquery 的 get、post 功能

jQuery 的 $.get、$.post 本质就是封装 ajax,底层是 XMLHttpRequest
image

const $ = {
  get(url, data, cb) {
    if (typeof data === 'function') {
      cb = data;
      data = null;
    }
    if (data) {
      const p = new URLSearchParams(data);
      url += (url.includes('?') ? '&' : '?') + p;
    }
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        let ret;
        try {
          ret = JSON.parse(xhr.responseText);
        } catch {
          ret = xhr.responseText;
        }
        cb(ret);
      }
    };
    xhr.send();
  },
  post(url, data, cb) {
    if (typeof data === 'function') {
      cb = data;
      data = null;
    }
    const xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    // 单独设置请求头
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        let ret;
        try {
          ret = JSON.parse(xhr.responseText);
        } catch {
          ret = xhr.responseText;
        }
        cb(ret);
      }
    };
    const p = new URLSearchParams(data);
    xhr.send(p);
  },
};

// 调用
$.get('/test', { id: 1 }, (res) => console.log(res));
$.post('/test', { name: 'xx' }, (res) => console.log(res));

29. 简要描述 web 前端性能需要考虑哪方面,你的优化思路是什么

image
image
image
image
image
image

30. readonly和disabled的区别

image
image
image

readonly:只读,可聚焦,表单提交会带上值;
disabled:禁用,置灰、不能聚焦,提交不会带上该字段

31. ajax 的工作原理

核心:利用 XMLHttpRequest(现代也用 fetch)对象,浏览器向服务器发 HTTP 请求,拿到数据后局部更新页面,不用刷新整个页面

AJAX 通过 XMLHttpRequest 对象发送异步 http 请求,拿到响应数据,JS 局部更新 DOM,无需整页刷新;
受浏览器同源策略限制

// 1. 创建 `XMLHttpRequest` 对象
const xhr = new XMLHttpRequest();

// 2. 初始化请求 `open(method, url, async)`
xhr.open('GET', '/api', true);

// 3. 监听响应回调 `onload / onreadystatechange`
// 等待服务端返回数据,拿到响应后操作 DOM,局部更新页面
xhr.onload = function () {
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log(xhr.responseText);
  }
};

// 4. 发送请求 `send()`
// - GET:`send()`
// - POST:`send(参数数据)`
xhr.send();

32. 简述javascript 的同源策略

同源策略是浏览器的安全机制,只存在浏览器环境,服务端之间通信不受限制

同源判定三要素:协议、域名、端口,三者必须全部相同才是同源,任一不同即为跨域

作用:防止恶意网站读取别的网站的敏感数据(cookie、storage、DOM、AJAX 响应),保护用户隐私

跨域请求是可以发送出去的,服务器也能收到并返回数据,只是浏览器拦截,不让 JS 读取响应结果

image

33. 如果设计中使用了非标准的字体,该如何去实现

先通过 font-face 定义字体,再引用

@font-face {
  font-family: 'MyFont'; /* 自定义字体名称,自己起 */
  src: url('./xxx.woff2') format('woff2'),
       url('./xxx.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

/* 使用 */
.text {
  font-family: 'MyFont', sans-serif;
}

34. HTTP 协议中,GET 和 POST 有什么区别?分别适用什么场景?

image
image
image

GET 参数在 url,默认缓存,语义是查询获取数据;
POST 参数放请求体,一般不缓存,语义是提交修改数据;
GET 适合查询,POST 适合提交新增
image

35. HTTP 协 议 中 , header信息里面,怎么控制页面失效时间

image
image
image
image

36. 判断变量是数组类型

Array.isArray()

[] instanceof Array

Object.prototype.toString.call([])  //返回 "[object Array]"

37. SQL注入和XSS漏洞

37.1 SQL注入

后端直接拼接用户输入到 SQL 语句,攻击者输入 SQL 片段,篡改原有 SQL 逻辑
image
image

37.2 XSS:跨站脚本攻击

恶意脚本注入到网页中,在受害者浏览器里执行 JS
image
image

38. 如何获取对象 a 拥有的所有属性:可枚举的、不可枚举的、不包括继承来的属性

Object.getOwnPropertyNames(a)

image

39. JS原型、原型链

40. JS中的变量提升

变量提升:JS 引擎在执行代码前,先对当前作用域扫描,把 var 声明的变量、function 函数声明提升到作用域顶部;
只是声明提升,赋值不会提升
image
image
image
image

JS 预解析阶段,var 变量、function 声明提升到作用域顶部;
var 提升后默认 undefined;
let/const 同样提升,但有暂时性死区,不能提前访问;
赋值操作留在原地不提升

41. 一般哪些操作会造成内存泄漏

image
image
image
image
image
image
image
image

42. WEB 应用从服务器主动推送 Data 到客户端有哪些方式

image

43. 前端开发的优化问题

  • 减少http请求次数:CSS Sprites,JS和CSS压缩源码、控制图片大小;网页GZip,CDN托管,data缓存,图片服务器

  • 前端模板JS+数据,减少由于HTML标签导致的宽带浪费,前端用变量保存AJAX请求结果,每次操作本地变量,不用多次重复请求

  • 用innerHTML替代DOM操作,减少DOM操作次数,优化JS性能

  • 当需要设置的样式很多时,用className,尽量少用style

  • 少用全局变量、缓存DOM节点查找的结果,减少IO读取操作

  • 避免使用CSS 表达式

  • 图片预加载,将样式放在顶部,将脚本放在底部,加上时间戳

  • 避免在页面的主体布局中使用table,table要等其中的内容完全下载之后全部显示出来,比div+css慢

44. 浏览器输入 URL 到页面渲染完整流程

image
image
image
image
image
image
image
image
image

45. map, filter, reduce

都是数组方法,不会改变原数组,返回新值;都是遍历,接收回调
image
image
image
image

数组转对象

const list = [{id:1,name:'a'},{id:2,name:'b'}]
const obj = list.reduce((pre, cur)=>{
  pre[cur.id] = cur.name
  return pre
}, {})
// {1:'a',2:'b'}

数组去重

const arr = [1,2,2,3,3,3]
const unique = arr.reduce((pre,cur)=>{
  if(!pre.includes(cur)) pre.push(cur)
  return pre
},[])
// [1,2,3]

posted @ 2026-11-23 18:32  songxia777  阅读(7)  评论(0)    收藏  举报