代码之家  ›  专栏  ›  技术社区  ›  GatesPlan

js方法存储的元素属性无法访问其属性

  •  0
  • GatesPlan  · 技术社区  · 4 年前

    formElement.ajax.ajaxmoduleA .. 这样地。

    formElement.ajaxA() 或者直接在提交事件上分配函数,但只有我能得到 Cannot read properties of undefined . 我想这是从 this

    class A {
        constructor() {
            this.a = 'a';
        }
    
        getA() {
            return this.a;
        }
    }
    
    el = document.querySelector('#updateNameForm');
    el.A = new A;
    el.B = el.A.getA;
    

    当我 el.A.getA.call() 控制台,同样的错误弹出。。如何将对象函数指定给元素属性?活动怎么样?

    4 回复  |  直到 4 年前
        1
  •  1
  •   Andy    4 年前
    1. bind 确保 this is being handled correctly .

    2. 您忘记在构造函数调用中添加开/闭括号: 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>
        2
  •  0
  •   Marco    4 年前

    可能是,因为你的语法是关闭的。您需要实例化新类或调用方法:

    el = document.querySelector('#updateNameForm');
    el.A = new A();
    el.B = el.A.getA();
    
        3
  •  0
  •   Ihar Dziamidau    4 年前

    请尝试修复该行:

    el.A = new A();
    
        4
  •  0
  •   Ran Turner    4 年前

    构造函数方法是类的一种特殊方法,用于创建和初始化该类的对象实例,该对象实例将通过使用“new”关键字按类名和 () 后面加括号

    class A {
        constructor() {
            this.a = 'a';
        }
    
        getA() {
            return this.a;
        }
    }
    
    el = document.querySelector('#updateNameForm');
    el.A = new A()
    el.B = el.A.getA;