如何创建功能方法

How to create functional Methods

我想要的方法是创建一个如下所示的自定义函数:

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;
}

所以这个函数应该处于更改内容或只是返回它的边缘。 不幸的是,它不能以这种方式工作。

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

我该如何解决这个问题?

将代码中的 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>