首頁 > web前端 > js教程 > 主體

功能

王林
發布: 2024-09-05 19:00:14
原創
485 人瀏覽過

功能

Fn简介:

语言的基本构建块。
最重要的概念。
Fn - 一段可以反复使用的代码。
{调用、运行、调用} Fn 的意思都是一样的。
Fn - 可以将数据作为参数,计算后返回数据作为结果。
Fn 调用被执行后返回的结果替换。
Fns 非常适合实施 DRY 原则
参数被传递,参数是占位符,它接收传递给 fn 的值。

Fn 声明与表达式:

Fn 声明以 fn 关键字开头。
Fn 表达式是匿名 fn,存储在变量内。然后存储 fn 的变量充当 fn。
匿名 fn defn 是一个表达式,该表达式产生一个值。 Fn 只是值。
Fn 不是 String、Number 类型。它是一个值,因此可以存储在变量中。
Fn 声明甚至可以在代码中定义之前调用,即它们被提升。这不适用于 Fn 表达式。
Fn 表达式强制用户首先定义 fns,然后再使用它们。一切都存储在变量中。
两者在 JS 中都有自己的位置,因此需要好好掌握。
Fn 表达式 = 本质上是存储在变量中的 fn 值

ES6 附带 Arrow Fn

单行隐式返回,多行需要显式返回。
箭头 fns 没有获得自己的“this”关键字
学习不是一个线性的过程,知识是逐渐积累的。你不可能一次性了解一件事的所有内容。

## Default parameters
const bookings = [];

const createBooking = function(flightNum, numPassengers=1, price= 100 * numPassengers){
  // It will work for parameters defined before in the list like numPassengers is defined before its used in expression of next argument else it won't work.
  // Arguments cannot be skipped also with this method. If you want to skip an argument, then manually pass undefined value for it which is equivalent to skipping an argument
  /* Setting default values pre-ES6 days.
  numPassengers = numPassengers || 1;
  price = price || 199;*/

// Using enhanced object literal, where if same property name & value is there, just write them once as shown below.
  const booking = {
    flightNum,
    numPassengers,
    price,
  };

  console.log(booking);
  bookings.push(booking);
}

createBooking('AI123');
/*
{
  flightNum: 'AI123',
  numPassengers: 1,
  price: 100
}
*/ 

createBooking('IN523',7);
/*
{
  flightNum: 'IN523',
  numPassengers: 7,
  price: 700
}
*/ 

createBooking('SJ523',5);
/*
{
  flightNum: 'SJ523',
  numPassengers: 5,
  price: 500
} 
*/ 

createBooking('AA523',undefined, 100000);
/*
{
  flightNum: 'AA523',
  numPassengers: 1,
  price: 100000
}
*/ 
登入後複製

从一个 fn 内部调用另一个 fn:

支持 DRY 原则的非常常见的技术。
支持可维护性
return 立即退出 fn
return = 从fn输出一个值,终止执行
fn 的三种写法,但工作方式相似,即输入、计算、输出
参数 = 接收 i/p 值的占位符,如 fn 的局部变量。

传递参数的工作原理,即值与引用类型

原语按值传递给 fn。原始价值保持不变。
对象通过 fn 的引用传递。原始值已更改。
JS 没有通过引用传递值。

不同 fns 与同一对象的交互有时会产生麻烦

fns 在 JS 中是一流的,因此我们可以编写 HO fns。

Fns 被视为值,只是对象的另一种“类型”。
由于对象是值,因此 fns 也是值。因此,也可以存储在变量中,附加为对象属性等。
此外,fns 也可以传递给其他 fns。前任。事件监听器-处理程序。
从 fns 返回。
Fns 是对象,对象在 JS 中有自己的方法-属性。因此,fn 可以具有可以调用它们的方法和属性。例如调用、申请、绑定等

高阶 Fn :接收另一个 fn 作为参数的 Fn,返回一个新的 fn 或两者。唯一可能的原因是 fns 在 JS 中是一流的
回调 fn 中传入的 Fn,将由 HOF 调用。

返回另一个 fn 的 Fns,即在闭包中。

First class fns 和 HOF 是不同的概念。

回调 Fns 广告:
允许我们创建抽象。更容易看到更大的问题。
将代码模块化为更小的块以供重复使用。

// Example for CB & HOF:
// CB1
const oneWord = function(str){
  return str.replace(/ /g,'').toLowerCase();
};

// CB2
const upperFirstWord = function(str){
    const [first, ...others] = str.split(' ');
    return [first.toUpperCase(), ...others].join(' ');
};

// HOF
const transformer = function(str, fn){
  console.log(`Original string: ${str}`);
  console.log(`Transformed string: ${fn(str)}`);
  console.log(`Transformed by: ${fn.name}`);
};
transformer('JS is best', upperFirstWord);
transformer('JS is best', oneWord);

// JS uses callbacks all the time.
const hi5 = function(){
  console.log("Hi");
};
document.body.addEventListener('click', hi5);

// forEach will be exectued for each value in the array.
['Alpha','Beta','Gamma','Delta','Eeta'].forEach(hi5);
登入後複製

Fns 返回另一个 fn。

// A fn returning another fn.
const greet = function(greeting){
  return function(name){
    console.log(`${greeting} ${name}`);
  }
}

const userGreet = greet('Hey');
userGreet("Alice");
userGreet("Lola");

// Another way to call
greet('Hello')("Lynda");

// Closures are widely used in Fnal programming paradigm.

// Same work using Arrow Fns. Below is one arrow fn returning another arrow fn.
const greetArr = greeting => name => console.log(`${greeting} ${name}`);

greetArr('Hola')('Roger');
登入後複製

“只有彻底理解某个主题,你才会进步”

调用(),应用(),绑定():

用于通过显式设置“this”关键字的值来设置其值。
call - 在“this”关键字的值之后获取参数列表。
apply - 在“this”关键字的值之后接受一个参数数组。它将从该数组中获取元素,并将其传递给函数。

bind():该方法创建一个新函数,并将 this 关键字绑定到指定对象。无论函数如何调用,新函数都会保留 .bind() 设置的 this 上下文。

call() 和 apply():这些方法使用指定的 this 值和参数调用函数。它们之间的区别在于 .call() 将参数作为列表,而 .apply() 将参数作为数组。

const lufthansa = {
  airline: 'Lufthansa',
  iataCode: 'LH',
  bookings: [],
  book(flightNum, name){
    console.log(`${name} booked a seat on ${this.airline} flight ${this.iataCode} ${flightNum}`);
    this.bookings.push({flight: `${this.iataCode} ${flightNum}`, name});
  },
};

lufthansa.book(4324,'James Bond');
lufthansa.book(5342,'Julie Bond');
lufthansa;


const eurowings = {
  airline: 'Eurowings',
  iataCode: 'EW',
  bookings: [],
};

// Now for the second flight eurowings, we want to use book method, but we shouldn't repeat the code written inside lufthansa object.

// "this" depends on how fn is actually called.
// In a regular fn call, this keyword points to undefined.
// book stores the copy of book method defuned inside the lufthansa object.
const book = lufthansa.book;

// Doesn't work
// book(23, 'Sara Williams');

// first argument is whatever we want 'this' object to point to.
// We invoked the .call() which inturn invoked the book method with 'this' set to eurowings 
// after the first argument, all following arguments are for fn.
book.call(eurowings, 23, 'Sara Williams');
eurowings;

book.call(lufthansa, 735, 'Peter Parker');
lufthansa;

const swiss = {
  airline: 'Swiss Airlines',
  iataCode: 'LX',
  bookings: []
}

// call()
book.call(swiss, 252, 'Joney James');

// apply()
const flightData = [652, 'Mona Lisa'];
book.apply(swiss, flightData);

// Below call() syntax is equivalent to above .apply() syntax. It spreads out the arguments from the array.
book.call(swiss, ...flightData);


登入後複製

以上是功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!