八股文-js

八股文-js
Xxcy欢迎阅读 js 八股文
📌 js
Q1:如何确认this的值
A:
1、全局执行环境中 this指向window
2、函数内部-this指向调用者1
2
3
4function func(){
console.log(this) //window
}
func()1
2
3
4
5function func(){
'use strict'
console.log(this) //undefined
}
func()
3、对象方法调用-this指向对象1
2
3
4
5
6
7const food= {
name: 'apple',
eat() {
console.log(this)
}
}
food.eat() //food对象
Q2:如何指定this的值
A:
1、调用时指定
call1
2
3
4
5
6
7
8function func(num1,num2){
console.log(this)
console.log(num1,num2)
}
const person = {
name: '张三'
}
func.call(person,1,2) //name: '张三' 1 2
apply(传入数组)1
func.apply(person,[3,4]) //name: '张三' 3 4
2、创建时指定
bind1
2const bindFunc = func.bind(person,666)
bindFunc(888) //name: '张三' 666 888
箭头函数1
2
3
4
5
6
7
8
9const food= {
name: 'apple',
eat() {
console.log(this)
setTimeout(()=>{
console.log(this) //food对象
},1000);
}
}
Q3:手写call方法
A:1
2
3
4
5
6
7Function.prototype.myCall = function(thisarg, ...args) {
const key = Symbol('key')
thisarg[key]= this //用[]解析
const res=thisarg[key](...args)
delete thisarg[key]
return res
}
Q4:手写apply方法
A:1
2
3
4
5
6
7Function.prototype.myApply = function(thisarg, args) {
const key = Symbol('key')
thisarg[key]= this //返回绑定this的新函数
const res =thisarg[key](...args)
delete thisarg[key]
return res
}
Q5:手写Bind方法
A:1
2
3
4
5
6Function.prototype.myBind = function(thisarg, ...args) {
return(...reargs)=>{
return call(thisarg, ...args, ...reargs)
}
}
Q6:javascript继承
A:
static静态
私有
Q7:函数柯里化
A:
把接受多个参数的函数变换成接受一个单一参数的函数,并且返回接受余下参数而且返回结果的新函数的技术1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16let nums=[]
function sum(...args){
nums.push(...args)
if (nums.length>=5){
const res=nums.slice(0,5).reduce((p,v)=>p+v,0)
nums=[]
return res
}else{
return sum
}
}
const typeOftest=type=>thing=>typeof thing===type
const isString=typeOftest('string')
Q8:基本的数据类型介绍,及值类型和引用类型的理解
A:
1. JavaScript 中的数据类型
JS 中共有 8 种基础数据类型:
- Undefined
- Null
- Boolean
- Number
- String
- Object
- Symbol(ES6 新增)
- BigInt(ES6 新增)
2. ES6 新增的数据类型
Symbol
- 代表独一无二的值。
- 常用来定义对象的唯一属性名,避免属性名冲突。
BigInt
- 可以表示任意大小的整数。
- 解决了 Number 类型最大安全整数
2^53 - 1
的限制。
3. 值类型 vs 引用类型
值类型(基本数据类型)
- 存储在 栈内存 中。
- 每个变量都有独立的存储空间。
- 包括:
Undefined
、Null
、Boolean
、Number
、String
、Symbol
、BigInt
。
引用类型
- 存储在 堆内存 中,变量存的是引用地址。
- 多个变量可能指向同一个对象。
- 包括:
Object
(如Array
、Function
、Date
等)。
4. 数据类型判断方法对比
1. typeof
- 优点:能判断所有基本数据类型和函数。
- 缺点:对
null
、对象、数组返回的都是object
,无法精确区分。
2. instanceof
- 作用:判断对象是否是某个构造函数的实例。
- 适用:对象类型。
- 局限:不能判断基本数据类型。
- 原理:判断某对象的原型链上,是否能找到指定构造函数的
prototype
。
示例:
1 | [] instanceof Array; // true |
2. Object.prototype.toString.call()
- 作用:精确判断所有数据类型。
- 适用:基本数据类型 + 内置对象类型(Array、Date、Error 等)。
- 局限:不能判断基本数据类型。
- 原理:返回 “[object Type]” 字符串。。
示例:
1 | Object.prototype.toString.call(2); // "[object Number]" |
5. 手写深拷贝
示例:
1 | // 自定义高性能的遍历方法 |