Откуда берется параметр? - PullRequest
0 голосов
/ 22 мая 2018
function createMathOperation(operator) {
  console.log(operator); //(augend, addend) => augend + addend
  return (value, other) => {
    return operator(value, other)
  }
}

const add = createMathOperation((augend, addend) => augend + addend)

add(1,2)//3

Я нашел приведенное выше определение функции из lodash.Я пытаюсь понять это, но безрезультатно.

Прямо внутри createMathOperation, я пытаюсь войти operator, и это значение

(augend, addend) => augend + addend

Я думаю, value иother это 1 и 2 но как?

И как return operator(value, other) работает, когда operator равен (augend, addend) => augend + addend

Может ли кто-нибудь преобразовать его в более длинную читаемую человеком форму для лучшего понимания?

Ответы [ 3 ]

0 голосов
/ 22 мая 2018

Это сущность функционального программирования, которую вы можете передать в функцию, вернуть функцию и вызвать функцию, полученную в качестве параметра:

function createMathOperation(operator) {
  console.log(operator); // This is a the function that performs the computation 
  // We return a new function (using arrow syntax) that receives 2 arguments and will call the original operator we passed in to createMathOperation
  // The code inside this function is not executed here, the function is not invoked. 
  // The caller can take the returned function and executed 0-n times as they wish. 
  return (value, other) => { 
    // when we invoke add this is the code that gets called and the arguments we pass to add end up in value and other
    console.log("Getting ready to compute " + value + " operator " + other); 
    return operator(value, other) // since operator is a function we just invoke it as we would any other function with the two arguments we got from whoever called us.
  }
}

// add will contain the wrapped function that has our extra console.log 
const add = createMathOperation((augend, addend) => augend + addend)

// The 'Getting ready ...' text has not been printed yet, nobody invoked the function that was returned yet, the next line will do so.
console.log(add(1,2)) 
// will output:
// Getting ready to compute 1 operator 2
// 3

Примечание к => - это просто синтаксический сахарпо выражению function он имеет дополнительную семантику около this, но для этого примера (augend, addend) => augend + addend эквивалентно function (augend, addend){ return augend + addend; }

0 голосов
/ 22 мая 2018

Ваш код в старом добром JS будет выглядеть так:

var createMathOperation = function(operator) {
  // operator is scope-locked within this operation wrapper
  console.log('operator:', operator);
  return function(value, other) {
    // The wrapper returns an anonymous function that acts as a call-wrapper
    // for your original function
    console.log('value:', value);
    console.log('other:', other);
    return operator(value, other)
  }
}

var add = createMathOperation(function(augend, addend) {
  // This is what is being called at line 9 - return operator(value, other)
  return augend + addend;
});

console.log('result 1+2:', add(1,2));

В общем, я не вижу особой пользы для всего этого, вы могли бы просто сделать const add = (a, v) => a + v; и получить тот же результат.

0 голосов
/ 22 мая 2018

createMathOperation возвращает функцию, которая добавляет два числа.Вот более читаемая версия:

function createMathOperation(fn) {
  console.log(fn);
  return function(value, other){
    return fn(value, other);
  };
}

const add = createMathOperation(function (augend, addend) {
  return augend + addend;
});

add(1,2)//3

Я переименовал 'operator' в 'fn', чтобы сделать его менее запутанным (подсветка синтаксиса по какой-то причине покрасила его в синий).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...