1

我正在尝试将一个类方法附加到一个元素,以便它引用该类的实例。

//例子

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)
    }
}

//调用

var route={
    init:()=>{      
        var form = new Form();
        var formBuild = form.assemble();
        document.body.appendChild(formBuild);
    }   
};
document.addEventListener('DOMContentLoaded',route.init);

问题:为什么 Form 类方法submit()返回的是按钮元素本身而不是实例化的类?

4

1 回答 1

-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;
    }   
}
于 2016-11-28T21:16:04.223 回答