如何创建函数式方法

How to create functional Methods

本文关键字:函数 方法 创建 何创建      更新时间:2023-09-26

我想做的是创建一个看起来像这样的自定义函数:

access('h1').content('Hello World');

这就是我试图实现这一目标的方式:

function access(Tag)
{
  var Element = document.getElementsByTagName(Tag)[0];
  this.content = function(Content)
  {
     if (Content !== undefined)
          return Element.innerHTML = Content;
     else return Element.innerHTML;
  }
  return Element;
}

因此,此功能将处于更改内容或只是返回内容的边缘。不幸的是,它不能以这种方式工作。

到目前为止,我玩了大约一个小时来重写它并自己找到解决方案,但我还没有成功,我也不知道如何向谷歌描述这个问题。

我该如何解决这个问题?

代码中的this替换为Element

function access(Tag)
    {
      var Element = document.getElementsByTagName(Tag)[0];
    
      Element.content = function(Content)
      {
         if (Content !== undefined)
              return Element.innerHTML = Content;
         else return Element.innerHTML;
      }
    
      return Element;
    }
    
access('h1').content('Hello World');
<h1>Hello</h1>

或者尝试这样的事情。

function access(Tag)
    {
      var Element = document.getElementsByTagName(Tag)[0];
    
      var content = function(Content)
      {
         if (Content !== undefined)
              return Element.innerHTML = Content;
         else return Element.innerHTML;
      }
    
      return {content: content};
    }
    
access('h1').content('Hello World');
<h1>Hello</h1>