【问题标题】:How to use a variable of second constructor function in Node.js? (using import/export)如何在 Node.js 中使用第二个构造函数的变量? (使用导入/导出)
【发布时间】:2019-07-08 19:48:19
【问题描述】:

我有 3 个不同的 .js 文件,它们之间通过 import/export 关键字链接。每个文件都有自己的特定功能,如下所示:


  1. Init.js:调用Event.jsTouch.js。将变量发送到 Event.js.

  2. Event.js:从Init.js接收变量并注册 event 到每个元素。

  3. Touch.js:识别来自Event.jsevent id,然后记录它。


一个问题是Touch.js 的构造函数根本不起作用。浏览器无法访问它。当我尝试将名为 AB 的局部变量记录下来时,它会一直触发 undefined

我发现唯一可能的方法是从Init.js 创建变量,将它们传递给Event.js,然后再次传递给Touch.js,就像我在下面所做的那样。

有没有办法使用自己构造函数的局部变量?

请看下面的代码:

//============== Init.js ==============
'use strict';
import {Event} from './event.js';
import { proTouch } from './touch.js';
const slider = (function() {
    class Slider {
        constructor(elem) {
            this.elem = document.querySelectorAll(elem);
            this.C = false;
            this.Event = new Event();
            this.Event.register(this.elem, 'mouseenter', proTouch.start, this.C);
        }
    }
    return {
        initialize: new Slider('.box')
    }
}());

//============== Event.js ==============

export class Event {
    constructor() {

    }
    register(node, eventName, callback, flag) {
        let bind = callback.bind(this);
        node.forEach(cur => {
            cur.addEventListener(eventName, (e) => bind(e, flag))
        })
    }
}


//============== Touch.js ==============

class Touch {
    constructor() {
        this.A = false;
        this.B = true; // <-- I want to use this constructor function.
    }
    start(e, flag) {
        console.log(e.type, this.A, this.B, flag); // <-- this.A and this.B fire undefined.
    }
}
const proTouch = new Touch();
export { proTouch }

【问题讨论】:

    标签: javascript node.js import constructor export


    【解决方案1】:

    在您的Event 类中,您将回调绑定到this。这是错误的,因为在这种情况下 thisEvent 实例并且不包含 ab 变量。删除该行。

    let bind = callback.bind(this);//Wrong. Delete this line.
    

    当您发送回调时,您希望将proTouch 绑定到start 方法。所以,绑定那里。

    this.Event.register(this.elem, 'mouseenter', proTouch.start.bind(proTouch), this.C);
    

    【讨论】:

    • 天哪,你救了我的命!非常感谢。
    猜你喜欢
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 2017-03-04
    • 2015-10-15
    • 2021-08-08
    相关资源
    最近更新 更多