简体   繁体   中英

How to use a variable of second constructor function in Node.js? (using import/export)

I have 3 different .js files that are linked between them by import/export keywords. Each of the files have their own specific functions like this:


  1. Init.js : Invokes Event.js and Touch.js . Send the variables to Event.js .

  2. Event.js : Receives the variables from Init.js and registers the event to each of the elements.

  3. Touch.js : Recognizes the event id from Event.js then logs it.


A problem is the constructor function of Touch.js doesn't work at all. The browser can't access to it. It keeps firing undefined when I try to log it the local variables called A and B .

The only possible way that I've found is to create the variables from Init.js , pass them to Event.js , and pass again to Touch.js like I've done below.

Are there any ways to use the local variables of its own constructor function?

See the code below:

//============== 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 }

In your Event class, you are binding the callback to this . That is wrong because in this context this is Event instance and doesn't contain a or b variable. Delete that line.

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

When you are Sending the callback you want to bind the proTouch to the start method. So, bind there.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM