八股文-js

欢迎阅读 js 八股文

📌 js

Q1:如何确认this的值

A:
1、全局执行环境中 this指向window
2、函数内部-this指向调用者

1
2
3
4
function func(){
console.log(this) //window
}
func()

1
2
3
4
5
function func(){
'use strict'
console.log(this) //undefined
}
func()

3、对象方法调用-this指向对象
1
2
3
4
5
6
7
const food= {
name: 'apple',
eat() {
console.log(this)
}
}
food.eat() //food对象

Q2:如何指定this的值

A:
1、调用时指定
call

1
2
3
4
5
6
7
8
function 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、创建时指定
bind

1
2
const bindFunc = func.bind(person,666)
bindFunc(888) //name: '张三' 666 888

箭头函数
1
2
3
4
5
6
7
8
9
const food= {
name: 'apple',
eat() {
console.log(this)
setTimeout(()=>{
console.log(this) //food对象
},1000);
}
}

Q3:手写call方法

A:

1
2
3
4
5
6
7
Function.prototype.myCall = function(thisarg, ...args) {
const key = Symbol('key')
thisarg[key]= this //用[]解析
const res=thisarg[key](...args)
delete thisarg[key]
return res
}