Я не понимаю применение в следующем коде в node js - PullRequest
0 голосов
/ 06 марта 2020

В следующем коде я не могу понять, какова роль применять. и как работает функция. Я прочитал много вопросов о применении, но до сих пор не могу понять это. Я также не понимаю, как он использует app.setup и после этого определяет его как функцию, и снова использует oldSetup в той же функции.

const oldSetup = app.setup;
app.setup = function(...args){
const RESULT = oldSetup.apply(this, args);
//some other codes come here
return RESULT;
}

1 Ответ

1 голос
/ 06 марта 2020

Я добавил комментарии, чтобы объяснить каждый шаг:

// assume this is the initial state
const app = {
  setup (a, b, c) {
    return { a, b, c }
  }
}

// save a pointer to the original function
const oldSetup = app.setup

// override the key with a new function. this is done by coverage tools for example
app.setup = function (...args) {
  // if you don't know how many parameters the original function will get, you can use
  // the rest parameter feature to get them all in an array
  // https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Functions_and_function_scope/rest_parameters
  // NOTE: you could use `arguments` too: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

  // since you don't know how many parameters the original function expects, you call the apply
  // that accept an array of parameter and it will spread:
  // args[0] = first argument
  // args[1] = second argument
  // and so on...
  // https://devdocs.io/javascript/global_objects/function/apply
  const RESULT = oldSetup.apply(this, args)

  // now you have the original result from the original function
  // you could change anything like "man in the middle" behaviour
  return RESULT
}

// it will print: { a: 1, b: 2, c: 3 }
console.log(app.setup(1, 2, 3, 4))
...