【问题标题】:Is creating objects in html and having functions considered bad practice in oop?是否在 html 中创建对象并在 oop 中使用被认为是不好的做法的函数?
【发布时间】:2019-05-18 16:37:34
【问题描述】:

我刚刚学习 JS 和 oop,想知道在 HTML 中创建对象和调用函数是否被认为是一种不好的做法。例如在下面的示例中的 onclick 事件中。还允许具有不是方法的功能吗?就像拥有一个函数,我将创建所有对象并调用它们的方法。

<input id="first_name" type="text" placeholder="First Name">
<input id="second_name" type="text" placeholder="Second Name">
<button onclick="const name = new Person('first_name', 'second_name', 'output'); name.writeName()">Show name</button>
<p id="output"></p>
class Person {
       constructor(first_name_id, second_name_id, output_id) {
           this.first_name = document.getElementById(first_name_id)
           this.second_name = document.getElementById(second_name_id)
           this.output = document.getElementById(output_id)
       }
       writeName() {
           return this.output.innerHTML = "Your name is" + this.first_name.value + " " + this.second_name.value
       }
   }

【问题讨论】:

  • 不鼓励 On-events(例如 &lt;a onclick=...),但在大多数其他形式中使用 JavaScript 却不是(evalwith 是罕见的例外)。

标签: javascript html oop


【解决方案1】:

使用旧式onxyz-attribute 事件处理程序的问题在于您只能在其中使用全局 函数。浏览器上的全局命名空间非常拥挤,因此最好避免在可以避免的情况下添加更多。

在您的示例中,您可能会考虑确保可以使用 CSS 选择器(或 id)识别按钮,然后使用现代技术(如 addEventListener)连接您的处理程序:

const theButton = document.querySelector("selector-for-the-button"); // or = document.getElementById("the-button-id");
theButton.addEventListener("click", function() {
    const name = new Person('first_name', 'second_name', 'output');
    name.writeName();
});

这样,Person 不必是全局的。

这在与 modules(无论是 JavaScript 的原生模块还是由 Webpack、Rollup 等提供的模块)结合时特别有用。

这是一个完整的例子,注意它没有使用任何全局变量:

{ // Scoping block to avoid creating globals
    class Person {
        constructor(first_name_id, second_name_id, output_id) {
            this.first_name = document.getElementById(first_name_id);
            this.second_name = document.getElementById(second_name_id);
            this.output = document.getElementById(output_id);
       }
       writeName() {
           return this.output.innerHTML = "Your name is " + this.first_name.value + " " + this.second_name.value;
       }
    }
    
    document.getElementById("show-name").addEventListener("click", function() {
        const name = new Person('first_name', 'second_name', 'output');
        name.writeName();
    });
}
<input id="first_name" type="text" placeholder="First Name">
<input id="second_name" type="text" placeholder="Second Name">
<button id="show-name">Show name</button>
<p id="output"></p>

【讨论】:

    【解决方案2】:

    在我看来,是的,这是一种非常糟糕的做法。要使某些东西可点击(如按钮),请在 单独的 JS 文件中使用此代码。

    // Anoymonous function
    varName.addEventListener("click", function(){
    alert("hi")
    })
    

    【讨论】:

      猜你喜欢
      • 2013-04-12
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      • 2018-01-25
      • 2011-04-10
      • 2018-08-11
      • 1970-01-01
      • 2018-07-03
      相关资源
      最近更新 更多