【问题标题】:How to pass argument from parent function to child function如何将参数从父函数传递给子函数
【发布时间】:2021-03-28 16:57:22
【问题描述】:

我有一个奇怪的任务:创建一个函数来创建其他函数(它们会将文本包装在 HTML 标记中)。

问题是我不知道如何在子函数中传递父参数。

function wrapperBuild(tag) {
  return new Function('text', "return '<' + tag + '>' + text + '<' + tag + '/>");
};

let wrapP = wrapperBuild("p");

console.log(wrapP('some text'));

//expected output: <p>some text</p>

【问题讨论】:

    标签: javascript


    【解决方案1】:

    有多种调用方式。

    而且你应该使用Template literals 而不是加入字符串。


    1

    function wrapperBuild(tag) {
      return function (text) {
        return `<${tag}>${text}</${tag}>`;
      };
    }
    
    let wrapP = wrapperBuild("p");
    
    console.log(wrapP("some text"));

    2

    function wrapperBuild(tag) {
      return function (text) {
        return `<${tag}>${text}</${tag}>`;
      };
    }
    let p = wrapperBuild("p")("some text");
    
    console.log(p);
    
    // OR - console.log(wrapperBuild("p")("some text"));

    3

    您可以通过使用箭头函数来进一步简化它...

    const wrapperBuild = (tag) => (text) => `<${tag}>${text}</${tag}>`;
    
    console.log(wrapperBuild("p")("some text"));



    一些有用的链接:


    【讨论】:

      【解决方案2】:

      尝试返回一个接受text 并返回html 的新函数。我用过arrow函数

      使用箭头函数

      function wrapperBuild(tag) {
        return (text) => {
          return `<${tag}> ${text} </${tag}>`;
        };
      }
      
      const fn = wrapperBuild("h1");
      console.log(fn("hello world"));

      使用老派功能

      function wrapperBuild(tag) {
        return function(text){
          return `<${tag}> ${text} </${tag}>`;
        };
      }
      
      const fn = wrapperBuild("h1");
      console.log(fn("hello world"));

      【讨论】:

      • 它有效,但我对语法感到困惑 :)
      • @Johny1995QQ 我正在做你正在做的事情,比如返回一个函数(在这种情况下是箭头函数),它接受一个参数text。所以这个函数fn 将运行并打印结果。但是您一定想知道标签,它来自哪里。它将来自closure
      猜你喜欢
      • 2023-01-22
      • 2018-08-28
      • 1970-01-01
      • 2013-11-30
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      相关资源
      最近更新 更多