我在方法中添加了一个新联系人:addToBook()
。首先,我检查字段(如果它们不为空),然后创建类LocalStorage
的实例,并传递字段值并从中生成JSON
。
我想在数组和LocalStorage
中看到新产品,但出现错误:
Uncaught TypeError: Can not read property 'push' of undefined"
帮我解决。
class Contacts {
constructor() {
// Storage Array
this.contacts = [];
}
addToBook() {
let isNull = forms.name.value != '' && forms.phone.value != '' &&
forms.email.value != '';
if (isNull) {
// format the input into a valid JSON structure
let obj = new LocalStorage(forms.name.value,
forms.phone.value, forms.email.value);
this.contacts.push(obj);
localStorage["addbook"] = JSON.stringify(this.contacts);
console.log(this.contacts);
}
console.log(this.contacts);
}
}
let contacts = new Contacts();
class Forms {
constructor() {
// Blocks
this.addNewContact = document.getElementById("addNewContact");
this.registerForm = document.querySelector('.addNewContact-form');
// Forms
this.fields = document.forms.register.elements;
this.name = this.fields[0].value;
this.phone = this.fields[1].value;
this.email = this.fields[2].value;
// Buttons
this.cancelBtn = document.getElementById("Cancel");
this.addBtn = document.getElementById("Add");
this.BookDiv = document.querySelector('.addbook');
// display the form div
this.addNewContact.addEventListener("click", (e) => {
this.registerForm.style.display = "block";
if (this.registerForm.style.display = "block") {
this.BookDiv.style.display = "none";
}
});
this.cancelBtn.addEventListener("click", (e) => {
this.registerForm.style.display = "none";
if (this.registerForm.style.display = "none") {
this.BookDiv.style.display = "block";
}
});
this.addBtn.addEventListener("click", contacts.addToBook);
}
}
let forms = new Forms();
class LocalStorage {
constructor(name, phone, email) {
this.name = name;
this.phone = phone;
this.email = email;
}
}
<div class="AddNewContact">
<button id="addNewContact" type="button">Add new contact</button>
<i class="fas fa-search "></i>
<input type="text" placeholder="SEARCH BY NAME">
<button id="ImportData" type="button">Import data to book</button>
</div>
<div class="addNewContact-form">
<form name="register">
<label for="name">Name</label><input type="text" id="name" class="formFields">
<label for="phone">Phone</label><input type="text" id="phone" class="formFields">
<label for="email">E-Mail</label><input type="text" id="email" class="formFields">
<br><br>
<button id="Add" type="button">Add Now</button><button id="Cancel" type="button">Cancel</button>
</form>
</div>
最佳答案
当传递对这样的函数的引用时:
this.addBtn.addEventListener("click", contacts.addToBook);
您松开对
this
的绑定。在this.contacts.push(obj);
中调用addToBook()
时所依赖的对象您可以将
this
的引用硬绑定到:this.addBtn.addEventListener("click", contacts.addToBook.bind(contacts);
您还可以传入一个在正确的上下文中显式调用
addToBook
的函数:this.addBtn.addEventListener("click", () => contacts.addToBook());
关于javascript - 为什么不向数组添加联系人的方法不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51341468/