0

I made an Ajax request module using javascript and I store its object to form element attribute formElement.ajax.ajaxmoduleA .. like this.

After that I want to use this function more easily something like .. formElement.ajaxA() or assign the function directly on submit event but only I can get is Cannot read properties of undefined. I presume this happens from this command inside of object.

class A {
    constructor() {
        this.a = 'a';
    }

    getA() {
        return this.a;
    }
}

el = document.querySelector('#updateNameForm');
el.A = new A;
el.B = el.A.getA;

When I el.A.getA.call() console, same error pops.. How can I assign object function into element property? How about on event?

GatesPlan
  • 465
  • 1
  • 4
  • 17

4 Answers4

1
  1. You need to use bind to ensure that this is being handled correctly.

  2. You forget to add open/close parentheses to your constructor call: new A().

class A {
    constructor() {
        this.a = 'a';
    }

    getA() {
        return this.a;
    }
}

const el = document.querySelector('#updateNameForm');
el.A = new A();
el.B = el.A.getA.bind(el.A);
console.log(el.B())
<div id="updateNameForm">Form</div>
Andy
  • 61,948
  • 13
  • 68
  • 95
0

It might be, because you're syntax is off. You need paranthesis to instantiate a new class or invoke a method:

el = document.querySelector('#updateNameForm');
el.A = new A();
el.B = el.A.getA();
Marco
  • 22,856
  • 9
  • 75
  • 124
0

Try fix the line:

el.A = new A();
Ihar Dziamidau
  • 337
  • 2
  • 9
0

The constructor method is a special method of a class for creating and initializing an object instance of that class that will be initialized by using the 'new' key word forward by the class name and the () parentheses after it

class A {
    constructor() {
        this.a = 'a';
    }

    getA() {
        return this.a;
    }
}

el = document.querySelector('#updateNameForm');
el.A = new A()
el.B = el.A.getA;
Ran Turner
  • 14,906
  • 5
  • 47
  • 53