
[英]If Javascript's native OOP is classless, what about the constructor? Doesn't that imply a class?
[英]OOP Question About Vanilla JS: The class's constructor won't accept the variable I'm feeding it as a parameter
我正在尝试通过练习来学习 OOP,但在这一点上我很困。 这是代码:
const itemEdit = () => {
let editIndex = buttonObj.editArr.indexOf(editID);
console.log(`the editIndex outside of the class is ${editIndex}`);
if (typeof editIndex != "undefined") {
editText = new htmlTextualizer(editIndex);
console.log(
"new class successfully created as variable is not 'undefined' type"
);
}
editText.printOut();
这是类/构造函数:
class htmlTextualizer {
constructor(curr) {
this.curr = curr;
}
printOut() {
console.log(this.curr);
}
}
output 要么是“未定义”,要么什么都没有。 该逻辑通常在 function 之外工作,所以我怀疑这与 scope 的启动有关,但我根本无法解决它。 援助将不胜感激。 谢谢。
如果未找到匹配项,JavaScript 的indexOf()
将返回-1
。 该检查应如下所示:
if (editIndex > -1) {…}
我不确定这是否会解决您的问题,但总的来说这是一个问题。
此外,如果该if
语句不正确,并且如果editText
未在您粘贴的内容之外的某个地方定义,则会出现错误,因为editText
undefined
(并且没有可用的方法)。
您的示例有几处不清楚,因为您引用了几个未定义的对象:buttonObj.editArr、editID、editText。
一般来说,我会更仔细地测试存在性。 您不想尝试访问未定义的 indexOf 方法。
我不确定你的业务逻辑到底是什么,但这里是我认为的方法:总是创建新的 object,除非 buttonObj.editArr 包含 editID。
以下是如何做到这一点:
const itemEdit = () => {
if ( !buttonObj ||
!buttonObj.editArr ||
(typeof buttonObj.editArr !== "object") ||
!editID ||
(buttonObj.editArr.indexOf(editID) < 0) ) {
editText = new htmlTextualizer(editIndex);
console.log("creating instance of class htmlTextualizer");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.