当前位置:网站首页>[interview question] 1369 when can't I use arrow function?
[interview question] 1369 when can't I use arrow function?
2022-07-03 01:27:00 【pingan8787】
Arrow function
Arrow functions are closely related to our work ; It can be said that the birth of arrow function , It has brought great convenience to our work . however What are the disadvantages of arrow functions ? When can't you use the arrow function ? Do you understand that ?
We think the arrow function is very advanced , Can avoid this The problem of , Arrow functions are used in all scenarios . Used in a scenario that cannot be used , There is a problem , You don't know what the problem is , Isn't that just adding to the mess ! Is it right? !
Here is a question for you first :
const obj = {
name: ' Zhang San ',
getName() {
return this.name
},
getName1: () => {
return this.name
}
}
obj.__proto__.getName2 = function() {
return this.name
}
obj.__proto__.getName3 = () => {
return this.name
}
console.log(' Ordinary function ',obj.getName())
console.log(' Ordinary function ',obj.getName2())
console.log(' Arrow function ',obj.getName1())
console.log(' Arrow function ',obj.getName3())
Copy code
What do you think will be output ?
Think quietly first !
3,2,1 Publish the answer !

If the answer is wrong , Don't lose heart , After all, the Internet has 35 Delay of , Affect your operation and thinking , After reading this article , Make sure you don't get it wrong !
What are the disadvantages of arrow functions ?
No, arguments, If you want to use , It can be used rest Parameters instead of . Here we define an arrow function, a normal function, and a function that uses rest Arrow function of parameter :
const fn1 = () => { console.log('arguments', arguments) } fn1(100, 200) function fn2(){ console.log('arguments', arguments) } fn2(100, 200) const fn3 = (...values) => { console.log('values', values) } fn3(100, 200) Copy code
image.png Unable to get apply、call、bind change this Point to Here we are defining an arrow function and an ordinary function
const fn3 = () => { console.log('this', this) } fn3() function fn4(){ console.log('this', this) } fn4() Copy code
Arrowhead function this It's his father's container this, Not determined at the time of implementation , It is defined at the time of definition .
Pictured above , We can find out , The arrow function is executed twice this It's all pointing Windows, Use call Nothing has changed , And ordinary functions The first time is pointing to Windows, The second time it became our incoming
When can't you use the arrow function ?
1. Object method , Not applicable to arrow function
const obj = {
name: ' Zhang San ',
getName() {
return this.name
},
getName1: () => {
return this.name
}
}
Copy code
We define... In the object Ordinary function :getName and Arrow function getName1, Next, let's call :
console.log(' Ordinary function ',obj.getName())
console.log(' Arrow function ',obj.getName1())
Copy code
Here is a meditation for you 3s What output ?
Publish the answer : We find that arrow function doesn't seem to get value !
Why in object methods , Arrowhead function this Point to something other than this object ?
this Always point to the caller of the function
In the arrow function ,this It refers to the object where it is defined , Instead of using the object . let me put it another way , Arrow function does not have its own this, Instead, it inherits from the parent scope this.
obj.getName()
in this
Point to the caller of the function , That is to say obj
example , therefore this.name = " Zhang San "
.
getName1()
Define through the arrow function , Arrow functions do not have their own this
, Will inherit the parent scope this
.
therefore obj.getName1()
Execution time , The scope at this time points to window
, and window
No definition age
attribute , All empty .
It can be concluded from the example that : It is not appropriate to use arrow functions for functions defined in an object .
2. In the prototype method , Not applicable to arrow function
const obj = {
name: ' Zhang San ',
}
obj.__proto__.getName = function() {
return this.name
}
obj.__proto__.getName1 = () => {
return this.name
}
Copy code
We define again in the object Ordinary function :getName and Arrow function getName1, Next, let's call :
console.log(obj.getName())
console.log(obj.getName1())
Copy code
Here is another meditation for you 3s What output ?
bang bang bang Publish the answer :
Why? ?
The reason for the problem is this Point to window object , This is very similar to using arrow functions to define methods in objects .
3. Constructors don't work either !
We have defined again Normal constructor :Foo and Arrow function Foo1, Next, let's call :
function Foo (name, sex) {
this.name = name
this.sex = sex
}
const Foo1 = (name, sex) => {
this.name = name
this.sex = sex
}
console.log(' Normal constructor :', new Foo(' Zhang San ', ' male '))
console.log(' Arrow function :', new Foo1(' Zhang San ', ' male '))
Copy code
Not only can't , I also reported an error !
Why? ?
Constructor is through new Keyword to generate object instances , The process of generating an object instance is also to bind the instance through the constructor this The process of , The arrow function does not have its own this. So you can't use arrows as constructors , You can't go through new Operator to call the arrow function .
4. Callback function in dynamic context
such as , We need to add a click event to a button :
const btn1 = document.getElementById('btn1')
btn1.addEventListener('click', () => {
this.innerHTML = 'clicked'
})
Copy code
If we don't need to use... In the callback this, Then there is no problem , however ! Using the this, Then the problem is huge !
Why? ?
Arrowhead function this Points to his parent scope ( This points to window), Instead of pointing to this button. At this time, we need to use ordinary functions .
5. Vue Life cycle and method Arrow functions cannot be used in

Why not ?
Vue It's essentially an object , We said that in object methods , Not applicable to arrow function . His essential and object methods , Not applicable arrow functions are the same .
So I have a question :Vue no way , As one of the big hot frames react Would you? ?
The answer is :react That's ok
because Vue The component is essentially a JS object ;React Components ( Not Hooks) He is essentially a ES6 Of class
If you don't believe me, we'll know by testing
class Man {
constructor(name, city) {
this.name = name
this.city = city
}
getName = () => {
return this.name
}
}
const f = new Man(' Li Si ',' Shanghai ')
console.log(f.getName())
Copy code

Focus on
Use arrow functions skillfully , Also for functions this( a key ) sensitive
Vue The component is essentially a JS object ;React Components ( Not Hooks) He is essentially a ES6 Of class, The two are different
The end
About this article :
source : It's a foreign persimmon
https://juejin.cn/post/7103702621369663518
边栏推荐
- How wide does the dual inline for bread board need?
- 异步、郵件、定時三大任務
- 2022 Jiangxi Provincial Safety Officer B certificate reexamination examination and Jiangxi Provincial Safety Officer B certificate simulation examination question bank
- 什么是调。调的故事
- ThinkPHP+Redis实现简单抽奖
- The latest analysis of tool fitter (technician) in 2022 and the test questions and analysis of tool fitter (technician)
- tail -f 、tail -F、tailf的区别
- 产业互联网的产业范畴足够大 消费互联网时代仅是一个局限在互联网行业的存在
- The meaning of wildcard, patsubst and notdir in makefile
- [day 29] given an integer, please find its factor number
猜你喜欢
leetcode:701. Insertion in binary search tree [BST insertion]
Correctly distinguish the similarities and differences among API, rest API, restful API and web service
Soft exam information system project manager_ Real topic over the years_ Wrong question set in the second half of 2019_ Morning comprehensive knowledge question - Senior Information System Project Man
C#应用程序界面开发基础——窗体控制(3)——文件类控件
Basic remote connection tool xshell
Assets, vulnerabilities, threats and events of the four elements of safe operation
[FPGA tutorial case 6] design and implementation of dual port RAM based on vivado core
Basic concept and implementation of overcoming hash
什么是调。调的故事
[androd] module dependency replacement of gradle's usage skills
随机推荐
Button wizard play strange learning - go back to the city to buy medicine and add blood
Druid database connection pool
给你一个可能存在 重复 元素值的数组 numbers ,它原来是一个升序排列的数组,并按上述情形进行了一次旋转。请返回旋转数组的最小元素。【剑指Offer】
The R language uses the ctree function in the party package to build conditional inference decision trees, uses the plot function to visualize the trained conditional inference decision tree, and the
【我的OpenGL学习进阶之旅】关于欧拉角、旋转顺序、旋转矩阵、四元数等知识的整理
MySQL基础用法02
R language ggplot2 visualization: use ggplot2 to display dataframe data that are all classified variables in the form of thermal diagram, and customize the legend color legend of factor
数学知识:能被整除的数—容斥原理
Dotconnect for PostgreSQL data provider
Leetcode 2097 - Legal rearrangement of pairs
Meituan dynamic thread pool practice ideas, open source
d,ldc构建共享库
Excel if formula determines whether the two columns are the same
Key wizard play strange learning - multithreaded background coordinate recognition
按键精灵打怪学习-回城买药加血
MySQL - database query - basic query
d,ldc構建共享庫
[FPGA tutorial case 5] ROM design and Implementation Based on vivado core
What are the trading forms of spot gold and what are the profitable advantages?
Concise analysis of redis source code 11 - Main IO threads and redis 6.0 multi IO threads