JavaScript - 如何创建原型函数以在选定元素中打印文本?

JavaScript - How to create a prototype function to print text in selected element?

我有一个快捷函数 id(),returns 一个元素就像普通的 document.getElementById() 一样。现在我想创建一个原型函数 print() 来替换 innerHTML。我已经测试了一些东西,我得到了下面的代码。它不起作用,我不太明白为什么......有人可以帮我解决这个问题吗?谢谢...

var id = function(item) {
 this.element = document.getElementById(item);
 return element;
}

id.prototype.print = function(value) {
 this.element.innerHTML = value;
}
document.body.onclick = function() {
  id('target').print('printed!');
}
#target {
  background: #00000055;
  padding: 10px;
  margin: 30px;
  display: inline-block;
  cursor: pointer;
}
<body>
  <div id="target">some text</div>
</body>

在调用构造函数创建 id 的实例时,您应该使用 new,并且不要显式 return 构造函数中的任何内容,以便实例是 returned 默认 - 然后,您可以使用关联的原型方法:

var id = function(item) {
 this.element = document.getElementById(item);
}

id.prototype.print = function(value) {
 this.element.innerHTML = value;
}
document.body.onclick = function() {
  const myElm = new id('target');
  myElm.print('printed!');
}
#target {
  background: #00000055;
  padding: 10px;
  margin: 30px;
  display: inline-block;
  cursor: pointer;
}
<body>
  <div id="target">some text</div>
</body>

当你做的时候

return element;

在构造函数的末尾,这将导致 returned 元素成为 plain HTML 元素,而不是 [=] 的实例18=](并且只有 id 的实例具有 print 方法)。

如果您不想在调用id时使用new,那么让id自己创建return具有 print 方法的实例(通过在 id 中调用 new 并 returning 它):

var id = function(item) {
  const instance = new MyElmClass(item);
  return instance;
}
var MyElmClass = function(item){
  this.element = document.getElementById(item);
};

MyElmClass.prototype.print = function(value) {
 this.element.innerHTML = value;
}
document.body.onclick = function() {
  const myElm = id('target');
  myElm.print('printed!');
}
#target {
  background: #00000055;
  padding: 10px;
  margin: 30px;
  display: inline-block;
  cursor: pointer;
}
<body>
  <div id="target">some text</div>
</body>

您的关闭,只需实例化对象即可,无需return。

var id = function(item) {
    this.element = document.getElementById(item);
}

id.prototype.print = function(value) {
    this.element.innerHTML = value;
}

var target = new id('target'); // <-- instantiate the object

document.body.onclick = function() {
  target.print('printed!');
}

正如其他人所指出的,您需要构造一个对象才能使用其原型。然而,一直 new id 很乏味,所以让我们将构造移到函数本身:

function id(item) {
  var obj = Object.create(id.prototype);
  obj.element = document.getElementById(item);
  return obj;
}

id.prototype.print = function(value) {
  this.element.innerHTML = value;
}

document.body.onclick = function() {
  id('target').print('printed!');
}
<body>
  <div id="target">some text</div>
</body>

现在,让我们做一些改进。为简洁起见,将 id 重命名为 $,使其接受任意选择器并将 print 重命名为 html:

function $(selector) {
  var obj = Object.create($.prototype)
  obj.element = document.querySelector(selector);
  return obj;
}

$.prototype.html = function(value) {
  this.element.innerHTML = value;
}

document.body.onclick = function() {
  $('#target').html('printed!');
}
<body>
  <div id="target">some text</div>
</body>

恭喜,我们刚刚发明了 jQuery! ;)