기능

王林
풀어 주다: 2024-09-05 19:00:14
원래의
485명이 탐색했습니다.

기능

Fns 소개:

언어의 기본 구성 요소
가장 필수적인 개념입니다.
Fn - 계속해서 사용할 수 있는 코드입니다.
{호출, 실행, 호출} Fn은 모두 같은 의미입니다.
Fn - 데이터를 인수로 취하고, 계산 후 결과로 데이터를 반환할 수 있습니다.
Fn 호출은 실행 후 반환된 결과로 대체됩니다.
Fns는 DRY 원칙을 구현하는 데 적합합니다
인수가 전달되고 매개변수는 fn에 전달된 값을 받는 자리 표시자입니다.

Fn 선언과 표현식:

Fn 선언은 fn 키워드로 시작됩니다.
Fn 표현식은 익명 fn이며 변수 내에 저장됩니다. 그러면 fn을 저장하는 변수가 fn 역할을 합니다.
익명의 fn defn은 표현식이고 표현식은 값을 생성합니다. Fn은 단지 값일 뿐입니다.
Fn은 문자열, 숫자 유형이 아닙니다. 값이므로 변수에 저장할 수 있습니다.
Fn 선언은 코드에 정의되기 전에도 호출할 수 있습니다. 즉, 끌어올려집니다. Fn 표현에는 적용되지 않습니다.
Fn 표현식은 사용자가 fns를 먼저 정의한 다음 나중에 사용하도록 강제합니다. 모든 것은 변수 안에 저장됩니다.
둘 다 JS에서 해당 위치를 차지하므로 제대로 숙달해야 합니다.
Fn 표현식 = 기본적으로 변수에 저장된 fn 값

Arrow Fn은 ES6와 함께 제공됩니다.

한 줄의 경우 암시적 반환, 여러 줄의 경우 명시적 반환이 필요합니다.
Arrow fns는 '이것' 키워드를 자체적으로 얻지 못합니다
학습은 선형적인 과정이 아니며, 지식은 점진적인 방식으로 축적됩니다. 한 번에 모든 것을 배울 수는 없습니다.

## 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에는 호출할 수 있는 속성뿐만 아니라 메서드도 있을 수 있습니다. Ex 통화, 신청, 바인딩 등

고차 Fn: 다른 fn을 인수로 수신하거나 새 fn을 반환하거나 둘 다를 반환하는 Fn입니다. fns는 JS의 일류이기 때문에 가능합니다
HOF에서 호출할 콜백 fn에 전달되는 Fn입니다.

다른 fn을 반환하는 Fns(예: 클로저)

퍼스트 클래스 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' 키워드 값 뒤에 인수 목록을 가져옵니다.
적용 - '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 학습자의 빠른 성장을 도와주세요!