国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Arrow Function Syntax
No parentheses syntax
Implicit return
Note the implicit return error
Cannot name arrow function
如何處理this關鍵字
匿名箭頭函數(shù)
不正常工作的情況
箭頭函數(shù)作為對象方法
箭頭函數(shù)與第三方庫
箭頭函數(shù)沒有arguments對象
總結(jié)
Home Web Front-end JS Tutorial This article will teach you about JS arrow functions

This article will teach you about JS arrow functions

Nov 10, 2022 pm 03:58 PM
javascript arrow function

This article will teach you about JS arrow functions

This article can let you know all about JavaScript arrow functions. We’ll show you how to use ES6’s arrow syntax, as well as some common mistakes to watch out for when using arrow functions in your code. You'll see lots of examples of how they work.

JavaScript’s arrow functions arrived with the release of ECMAScript 2015, also known as ES6. Due to their concise syntax and handling of the this keyword, arrow functions have quickly become a favorite feature among developers.

Arrow Function Syntax

Functions are like recipes in which you store useful instructions to accomplish something you need to happen in your program, such as performing an action or return a value. By calling a function, you execute the steps contained in the recipe. You can do this every time you call the function without having to rewrite the recipe again and again.

Here's the standard way to declare a function and call it in JavaScript:

//?function?declaration
function?sayHiStranger()?{
??return?'Hi,?stranger!'
}

//?call?the?function
sayHiStranger()

You can also write the same function as a function expression, just like this:

const?sayHiStranger?=?function?()?{
??return?'Hi,?stranger!'
}

JavaScript Arrow functions are always expressions. Here's how to rewrite the function above using arrow notation:

const?sayHiStranger?=?()?=>?'Hi,?stranger'

The benefits of doing this include:

  • Only one line of code
  • NofunctionKeywords
  • NoreturnKeywords
  • No braces{}

In JavaScript, functions A first-class citizen. You can store functions in variables, pass them as arguments to other functions, and return them as values ??from other functions. You can use JavaScript arrow functions to do all of these things.

No parentheses syntax

In the above example, the function has no parameters. In this case, you must add an empty pair of parentheses () before the fat arrow symbol (=>). Same thing when there are multiple parameters:

const getNetflixSeries = (seriesName, releaseDate) => `The ${seriesName} series was released in ${releaseDate}`
// call the function
console.log(getNetflixSeries('Bridgerton', '2020') )
// output: The Bridgerton series was released in 2020

If there is only one parameter, you can omit the parentheses (you don't have to, but you can):

const favoriteSeries = seriesName => seriesName === "Bridgerton" ? "Let's watch it" : "Let's go out"
// call the function
console.log(favoriteSeries("Bridgerton"))
// output: "Let's watch it"

When you do Always be careful. For example, if you decide to use default parameters, you must wrap them in parentheses:

// with parentheses: correct
const bestNetflixSeries = (seriesName = "Bridgerton") => `${seriesName} is the best`
// outputs: "Bridgerton is the best"
console.log(bestNetflixSeries())

// no parentheses: error
const bestNetflixSeries = seriesName = "Bridgerton" => `${seriesName} is the best`
// Uncaught SyntaxError: invalid arrow-function arguments (parentheses around the arrow-function may help)

Implicit return

When there is only one expression in the function body, You can make ES6's arrow syntax more concise. You can put everything on one line, remove the curly braces, and remove the return keyword.

You've seen how these nifty one-liners work in the example above. The following orderByLikes() function returns an array of Netflix episode objects, sorted by the highest number of likes:

// using the JS sort() function to sort the titles in descending order 
// according to the number of likes (more likes at the top, fewer at the bottom
const orderByLikes = netflixSeries.sort((a, b) => b.likes - a.likes)

// call the function 
// output:the titles and the n. of likes in descending order
console.log(orderByLikes)

This way of writing is cool, but pay attention to the readability of the code. Especially when sorting through a bunch of arrow functions using single-line and bracketless ES6 arrow syntax. Like this example:

const greeter = greeting => name => `${greeting}, ${name}!`

What happened there? Try using the regular function syntax:

function greeter(greeting) {
  return function(name) {
    return `${greeting}, ${name}!` 
  }
}

Now you can quickly see how the external function greeter has parameters greeting, and returns an anonymous function. This inner function takes another parameter called name and returns a string using the values ??of greeting and name. Here's how to call the function:

const myGreet = greeter('Good morning')
console.log( myGreet('Mary') )   

// output: 
"Good morning, Mary!"

Note the implicit return error

When your JavaScript arrow function contains more than one statement, you need to wrap them all within curly braces statement and use the return keyword.

In the following code, the function creates an object containing the titles and summaries of several Netflix episodes:

const seriesList = netflixSeries.map( series => {
  const container = {}
  container.title = series.name 
  container.summary = series.summary

  // explicit return
  return container
} )

.map() in the function Arrow functions expand in a series of statements, returning an object at the end of the statement. This makes the use of braces around function bodies unavoidable.

Also, since curly braces are being used, implicit return is not an option. You must explicitly use the return keyword.

If your function uses implicit return to return an object literal, you need to use parentheses to wrap the object literal. Failure to do so will result in an error because the JavaScript engine incorrectly parses the braces of an object literal as braces of a function. As you just noticed, when you use curly braces in an arrow function, you cannot omit the return keyword.

A shorter version of the preceding code demonstrates this syntax:

// Uncaught SyntaxError: unexpected token: ':'
const seriesList = netflixSeries.map(series => { title: series.name });

// Works fine
const seriesList = netflixSeries.map(series => ({ title: series.name }));

Cannot name arrow function

in function key Functions that have no name identifier between the word and parameter list are called anonymous functions. Here's what a regular anonymous function expression looks like:

const anonymous = function() {
  return 'You can\'t identify me!' 
}

Arrow functions are all anonymous functions:

const anonymousArrowFunc = () => 'You can\'t identify me!'

Starting with ES6, variables and methods can be passed through the syntax position of the anonymous function, using name attribute to infer its name. This makes it possible to identify the function when checking its value or reporting an error.

Use anonymousArrowFunc Check it out:

console.log(anonymousArrowFunc.name)
// output: "anonymousArrowFunc"

需要注意的是,只有當匿名函數(shù)被分配給一個變量時,這個可以推斷的name屬性才會存在,正如上面的例子。如果你使用匿名函數(shù)作為回調(diào)函數(shù),你就會失去這個有用的功能。在下面的演示中,.setInterval()方法中的匿名函數(shù)無法利用name屬性:

let counter = 5
let countDown = setInterval(() => {
  console.log(counter)
  counter--
  if (counter === 0) {
    console.log("I have no name!!")
    clearInterval(countDown)
  }
}, 1000)

這還不是全部。這個推斷的name屬性仍然不能作為一個適當?shù)臉俗R符,你可以用它來指代函數(shù)本身--比如遞歸、解除綁定事件等。

如何處理this關鍵字

關于箭頭函數(shù),最重要的一點是它們處理this關鍵字的方式。特別是,箭頭函數(shù)內(nèi)的this關鍵字不會重新綁定。

為了說明這意味著什么,請查看下面的演示。

這里有一個按鈕。點擊按鈕會觸發(fā)一個從5到1的反向計數(shù)器,它顯示在按鈕本身。

<button class="start-btn">Start Counter</button>

...

const startBtn = document.querySelector(".start-btn");

startBtn.addEventListener(&#39;click&#39;, function() {
  this.classList.add(&#39;counting&#39;)
  let counter = 5;
  const timer = setInterval(() => {
    this.textContent = counter 
    counter -- 
    if(counter < 0) {
      this.textContent = &#39;THE END!&#39;
      this.classList.remove(&#39;counting&#39;)
      clearInterval(timer)
    }
  }, 1000) 
})

注意到.addEventListener()方法里面的事件處理器是一個常規(guī)的匿名函數(shù)表達式,而不是一個箭頭函數(shù)。為什么呢?如果在函數(shù)內(nèi)部打印this的值,你會看到它引用了監(jiān)聽器所連接的按鈕元素,這正是我們所期望的,也是程序按計劃工作所需要的:

startBtn.addEventListener(&#39;click&#39;, function() {
  console.log(this)
  ...
})

下面是它在Firefox開發(fā)人員工具控制臺中的樣子:

This article will teach you about JS arrow functions

然后,嘗試使用箭頭函數(shù)來替代常規(guī)函數(shù),就像這樣:

startBtn.addEventListener(&#39;click&#39;, () => {
  console.log(this)
  ...
})

現(xiàn)在,this不再引用按鈕元素。相反,它引用Window對象:

This article will teach you about JS arrow functions

這意味著,如果你想要在按鈕被點擊之后,使用this來為按鈕添加class,你的代碼就無法正常工作:

// change button&#39;s border&#39;s appearance
this.classList.add(&#39;counting&#39;)

下面是控制臺中的錯誤信息:

This article will teach you about JS arrow functions

當你在JavaScript中使用箭頭函數(shù),this關鍵字的值不會被重新綁定。它繼承自父作用域(也稱為詞法作用域)。在這種特殊情況下,箭頭函數(shù)被作為參數(shù)傳遞給startBtn.addEventListener()方法,該方法位于全局作用域中。因此,函數(shù)處理器中的this也被綁定到全局作用域中--也就是Window對象。

因此,如果你想讓this引用程序中的開始按鈕,正確的做法是使用一個常規(guī)函數(shù),而不是一個箭頭函數(shù)。

匿名箭頭函數(shù)

在上面的演示中,接下來要注意的是.setInterval()方法中的代碼。在這里,你也會發(fā)現(xiàn)一個匿名函數(shù),但這次是一個箭頭函數(shù)。為什么?

請注意,如果你使用常規(guī)函數(shù),this值會是多少:

const timer = setInterval(function() {
  console.log(this)
  ...
}, 1000)

button元素嗎?并不是。這個值將會是Window對象!

事實上,上下文已經(jīng)發(fā)生了變化,因為現(xiàn)在this在一個非綁定的或全局的函數(shù)中,它被作為參數(shù)傳遞給.setInterval() 。因此,this關鍵字的值也發(fā)生了變化,因為它現(xiàn)在被綁定到全局作用域。

在這種情況下,一個常見的hack手段是包括另一個變量來存儲this關鍵字的值,這樣它就會一直指向預期的元素--在這種情況下,就是button元素:

const that = this
const timer = setInterval(function() {
  console.log(that)
  ...
}, 1000)

你也可以使用.bind()來解決這個問題:

const timer = setInterval(function() {
  console.log(this)
  ...
}.bind(this), 1000)

有了箭頭函數(shù),問題就徹底消失了。下面是使用箭頭函數(shù)時this的值:

const timer = setInterval( () => { 
  console.log(this)
  ...
}, 1000)

This article will teach you about JS arrow functions

這次,控制臺打印了button,這就是我們想要的。事實上,程序要改變按鈕的文本,所以它需要this來指代button元素:

const timer = setInterval( () => { 
  console.log(this)
 // the button&#39;s text displays the timer value
  this.textContent = counter
}, 1000)

箭頭函數(shù)沒有自己的this上下文。它們從父級繼承this的值,正是因為這個特點,在上面這種情況下就是很好的選擇。

不正常工作的情況

箭頭函數(shù)并不只是在JavaScript中編寫函數(shù)的一種花里胡哨的新方法。它們有自己的局限性,這意味著在有些情況下你不想使用箭頭函數(shù)。讓我們看看更多的例子。

箭頭函數(shù)作為對象方法

箭頭函數(shù)作為對象上的方法不能很好地工作。

考慮這個netflixSeries對象,上面有一些屬性和一系列方法。調(diào)用console.log(netflixSeries.getLikes()) 應該會打印一條信息,說明當前喜歡的人數(shù)。console.log(netflixSeries.addLike())應該會增加一個喜歡的人數(shù),然后在控制臺上打印新值:

const netflixSeries = {
  title: &#39;After Life&#39;, 
  firstRealease: 2019,
  likes: 5,
  getLikes: () => `${this.title} has ${this.likes} likes`,
  addLike: () => {  
    this.likes++
    return `Thank you for liking ${this.title}, which now has ${this.likes} likes`
  } 
}

相反,調(diào)用.getLikes()方法返回&#39;undefined has NaN likes&#39;,調(diào)用.addLike()方法返回&#39;Thank you for liking undefined, which now has NaN likes&#39;。因此,this.titlethis.likes未能分別引用對象的屬性titlelikes。

這次,問題出在箭頭函數(shù)的詞法作用域上。對象方法中的this引用的是父對象的范圍,在本例中是Window對象,而不是父對象本身--也就是說,不是netflixSeries對象。

當然,解決辦法是使用常規(guī)函數(shù):

const netflixSeries = {
  title: &#39;After Life&#39;, 
  firstRealease: 2019,
  likes: 5,
  getLikes() {
    return `${this.title} has ${this.likes} likes`
  },
  addLike() { 
    this.likes++
    return `Thank you for liking ${this.title}, which now has ${this.likes} likes`
  } 
}

// call the methods 
console.log(netflixSeries.getLikes())
console.log(netflixSeries.addLike())

// output: 
After Life has 5 likes
Thank you for liking After Life, which now has 6 likes

箭頭函數(shù)與第三方庫

另一個需要注意的問題是,第三方庫通常會綁定方法調(diào)用,因此this值會指向一些有用的東西。

比如說,在Jquery事件處理器內(nèi)部,this將使你能夠訪問處理器所綁定的DOM元素:

$(&#39;body&#39;).on(&#39;click&#39;, function() {
  console.log(this)
})
// <body>

但是如果我們使用箭頭函數(shù),正如我們所看到的,它沒有自己的this上下文,我們會得到意想不到的結(jié)果:

$(&#39;body&#39;).on(&#39;click&#39;, () =>{
  console.log(this)
})
// Window

下面是使用Vue的其他例子:

new Vue({
  el: app,
  data: {
    message: &#39;Hello, World!&#39;
  },
  created: function() {
    console.log(this.message);
  }
})
// Hello, World!

created鉤子內(nèi)部,this被綁定到Vue實例上,因此會顯示&#39;Hello, World!&#39;信息。

然而如果我們使用箭頭函數(shù),this將會指向父作用域,上面沒有message屬性:

new Vue({
  el: app,
  data: {
    message: &#39;Hello, World!&#39;
  },
  created: () => {
    console.log(this.message);
  }
})
// undefined

箭頭函數(shù)沒有arguments對象

有時,你可能需要創(chuàng)建一個具有無限參數(shù)個數(shù)的函數(shù)。比如,假設你想創(chuàng)建一個函數(shù),列出你最喜歡的奈飛劇集,并按照偏好排序。然而,你還不知道你要包括多少個劇集。JavaScript提供了arguments對象。這是一個類數(shù)組對象(不是完整的數(shù)組),在調(diào)用時存儲傳遞給函數(shù)的值。

嘗試使用箭頭函數(shù)實現(xiàn)此功能:

const listYourFavNetflixSeries = () => {
  // we need to turn the arguments into a real array 
  // so we can use .map()
  const favSeries = Array.from(arguments) 
  return favSeries.map( (series, i) => {
    return `${series} is my #${i +1} favorite Netflix series`  
  } )
  console.log(arguments)
}

console.log(listYourFavNetflixSeries(&#39;Bridgerton&#39;, &#39;Ozark&#39;, &#39;After Life&#39;))

當你調(diào)用該函數(shù)時,你會得到以下錯誤:Uncaught ReferenceError: arguments is not defined。這意味著arguments對象在箭頭函數(shù)中是不可用的。事實上,將箭頭函數(shù)替換成常規(guī)函數(shù)就可以了:

const listYourFavNetflixSeries = function() {
   const favSeries = Array.from(arguments) 
   return favSeries.map( (series, i) => {
     return `${series} is my #${i +1} favorite Netflix series`  
   } )
   console.log(arguments)
 }
console.log(listYourFavNetflixSeries(&#39;Bridgerton&#39;, &#39;Ozark&#39;, &#39;After Life&#39;))

// output: 
["Bridgerton is my #1 favorite Netflix series",  "Ozark is my #2 favorite Netflix series",  "After Life is my #3 favorite Netflix series"]

因此,如果你需要arguments對象,你不能使用箭頭函數(shù)。

但如果你真的想用一個箭頭函數(shù)來復制同樣的功能呢?你可以使用ES6剩余參數(shù)(...)。下面是你該如何重寫你的函數(shù):

const listYourFavNetflixSeries = (...seriesList) => {
   return seriesList.map( (series, i) => {
     return `${series} is my #${i +1} favorite Netflix series`
   } )
 }

總結(jié)

通過使用箭頭函數(shù),你可以編寫帶有隱式返回的單行代碼,以解決JavaScript中this關鍵字的綁定問題。箭頭函數(shù)在數(shù)組方法中也很好用,如.map()、.sort()、.forEach()、.filter()、和.reduce()。但請記?。杭^函數(shù)并不能取代常規(guī)的JavaScript函數(shù)。記住,只有當箭形函數(shù)是正確的工具時,才能使用它。

以上就是本文的所有內(nèi)容,如果對你有所幫助,歡迎點贊收藏轉(zhuǎn)發(fā)~

原文鏈接:www.sitepoint.com/arrow-funct…

作者:Maria Antonietta Perna

【推薦學習:javascript視頻教程

The above is the detailed content of This article will teach you about JS arrow functions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles