如何在 javascript 原型的控制台中调用函数?

How to call functions in a console in a javascript prototype?

我使用了下面对我最初问题的回答中的以下代码:

const myForm = {
  text : "Hello",
  span1: '<span>',
  span2: '</span>',
  p1: '<p>',
  p2: '</p>',
  span: function() {
this.text = this.span1 + this.text + this.span2;
return this;
  },
  p: function() {
this.text = this.p1 + this.text + this.p2;
return this;
  }
};

console.log(myForm.p().span().text)

如何在console.log(myForm.p().span())中修改接收<p><span>Hello</span></p>的代码,因为它添加标签的顺序错了,先p( ) 而不是 span() 我首先需要 span() 围绕文本而不是 p() ?

修改p函数,取一个变量包围,用myForm.span()作为输入

var myForm = {
  span1: '<span>',
  span2: '</span>',
  p1: '<p>',
  p2: '</p>',
  span: function() {
    return this.span1 + "Hello" + this.span2
  },
  p: function(target) {
    return this.p1 + target + this.p2
  },
};

console.log(myForm.p(myForm.span()))

问题是,由于您希望方法是可链接的,因此每个方法都必须 return this,而不是字符串。这意味着 console.log(myForm.p().span()) 将 return 完整的对象。您可以执行以下操作:

const myForm = {
  text : "Hello",
  span1: '<span>',
  span2: '</span>',
  p1: '<p>',
  p2: '</p>',
  span: function() {
    this.text = this.span1 + this.text + this.span2;
    return this;
  },
  p: function() {
    this.text = this.p1 + this.text + this.p2;
    return this;
  }
};

console.log(myForm.span().p().text)

您甚至可以走得更远,例如制作一个单一的参数化方法:

const myForm = {
  text : "Hello",
  wrap : function(elems) {
    for(let elem of elems.split(",")){
      this.text = `<${elem}>${this.text}</${elem}>`
    }
    return this;
  }
};

console.log(myForm.wrap("span,p,div,header").text);

使用createElementcreateTextNodeappendChild

function addElement () {
  // create a new span and p element
  const newP = document.createElement("p");
  const newSpan = document.createElement("span");

  // and give it some content
  var textnode = document.createTextNode("Water");
  newSpan.appendChild(textnode)
  // add the text node to the newly created span
  newP.appendChild(newSpan);

  // add the newly created element and its content into the DOM
  const currentDiv = document.getElementById("div1");
  document.body.insertBefore(newP, currentDiv);
}

addElement()