关于香草 JS 的 OOP 问题:类的构造函数不会接受我将其作为参数输入的变量



我正试图通过实践来学习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);
}
}

输出要么是"未定义",要么什么都没有。逻辑通常在函数之外工作,所以我怀疑这与启动范围有关,但我只是无法解决它。我们将不胜感激。谢谢

如果未找到匹配项,JavaScript的indexOf()将返回-1。那张支票应该是这样的:
if (editIndex > -1) {…}

我不确定这是否能解决你的问题,但这是一个普遍的问题。

此外,如果if语句不为真,并且editText没有在粘贴到此处的内容之外定义,则会出现错误,因为editTextundefined(并且没有可用的方法(。

由于引用了几个未定义的对象,因此您的示例中有几点不清楚:buttonObj.editArr、editID、editText。

总的来说,我会更仔细地对待存在性测试。您不想尝试访问未定义的东西的indexOf方法。

我不确定您的业务逻辑到底是什么,但以下是我认为的方法:始终创建新对象,除非buttonObj.editArr包含editID。

以下是如何做到这一点:

const itemEdit = () => {
if ( !buttonObj || 
!buttonObj.editArr ||
(typeof buttonObj.editArr !== "object") ||
!editID ||
(buttonObj.editArr.indexOf(editID) < 0) ) {
editText = new htmlTextualizer(buttonObj.editArr.indexOf(editID));
console.log("creating instance of class htmlTextualizer");
}
}

最新更新