【发布时间】: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(例如
<a onclick=...),但在大多数其他形式中使用 JavaScript 却不是(eval和with是罕见的例外)。
标签: javascript html oop