Skip to content

Исправление ошибки в функции карирования #2038

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Mokss
Copy link

@Mokss Mokss commented Apr 5, 2025

Описание

В примере учебника функции карирования явно добавлен метод apply, указывающий, что мы должны помнить о контексте. Но пример не учел, что возвращаемую рекурсивно функцию curried так же оборачивают в анонимную функцию, у которой свой контекст this, из-за чего происходит потеря изначального контекста и пример работает не правильно.
Замена анонимной функции на стрелочную решает проблему, так как стрелочная функция не имеет своего this, и берет его у своего родителя.

Вот пример где ошибку легко воспроизвести

function curry(func) {

  return function curried(...args) {
    if (args.length >= func.length) {
      return func.apply(this, args);
    } else {
      return function(...args2) {
        return curried.apply(this, args.concat(args2));
      }
    }
  };

}

function testFn(biba, boba) {
  return this.prefix + biba + ', ' + boba;
}

const obj = {
  prefix: "Mokss: ",
  test: curry(testFn)
};

console.log(obj.test("Biba")("Boba")); // undefinedBiba, Boba

Пример с фиксом, где код работает ожидаемо

function curry(func) {

  return function curried(...args) {
    if (args.length >= func.length) {
      return func.apply(this, args);
    } else {
      return (...args2) => {
        return curried.apply(this, args.concat(args2));
      }
    }
  };

}

function testFn(biba, boba) {
  return this.prefix + biba + ', ' + boba;
}

const obj = {
  prefix: "Mokss: ",
  test: curry(testFn)
};

console.log(obj.test("Biba")("Boba")); // Mokss: Biba, Boba

@javascript-translate-bot javascript-translate-bot added review needed Review needed, please approve or request changes labels Apr 5, 2025
@javascript-translate-bot javascript-translate-bot requested a review from a team April 5, 2025 17:15
@CLAassistant
Copy link

CLAassistant commented Apr 5, 2025

CLA assistant check
All committers have signed the CLA.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
review needed Review needed, please approve or request changes
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants