我正在尝试将一个类方法附加到一个元素,以便它引用该类的实例。
//实施例
class Default{
constructor(){
this.parent = null
}
assemble(){
var form = document.createElement('form'); //CREATE FORM ELEMENT
var btn = document.createElement('button'); //CREATE BUTTON ELEMENT
this.parent = form; //DECLARE PARENT (CONSTRUCTOR)
btn.type = 'button';
btn.innerHTML = 'click me';
btn.addEventListener('click',this.submit);
form.appendChild(btn);
return form;
}
}
class Form extends Default{
submit(){
console.log(this.parent); //should return instantiated form value for property parent but doesn't (undefined)
console.log(this); //returns reference to the button element itself not the class (Form)
}
}
// CALLED
var route={
init:()=>{
var form = new Form();
var formBuild = form.assemble();
document.body.appendChild(formBuild);
}
};
document.addEventListener('DOMContentLoaded',route.init);
问题:为什么Form类方法submit()
返回按钮元素本身而不是实例化类?
答案 0 :(得分:-3)
class Default{
constructor(){
this.parent = null
}
assemble(){
var form = document.createElement('form'); //CREATE FORM ELEMENT
var btn = document.createElement('button'); //CREATE BUTTON ELEMENT
btn.parent = form; //DECLARE PARENT (CONSTRUCTOR)
btn.type = 'button';
btn.innerHTML = 'click me';
btn.addEventListener('click',this.submit);
form.appendChild(btn);
return form;
}
}