[英]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. 我有3个不同的.js
文件,这些文件之间通过import/export
关键字链接。 Each of the files have their own specific functions like this: 每个文件都有自己的特定功能,如下所示:
Init.js
: Invokes Event.js
and Touch.js
. Init.js
:调用Event.js
和Touch.js
。 Send the variables to Event.js
. 将变量发送到Event.js
。
Event.js
: Receives the variables from Init.js
and registers the event
to each of the elements. Event.js
:从Init.js
接收变量, Init.js
event
注册到每个元素。
Touch.js
: Recognizes the event
id from Event.js
then logs it. Touch.js
:从Event.js
识别event
ID,然后将其记录。
A problem is the constructor function of Touch.js
doesn't work at all. 一个问题是Touch.js
的构造函数Touch.js
不起作用。 The browser can't access to it. 浏览器无法访问它。 It keeps firing undefined
when I try to log it the local variables called A
and B
. 当我尝试将其记录为A
和B
的局部变量时,它始终保持undefined
状态。
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. 我发现的唯一可能的方法是从Init.js
创建变量,将它们传递给Event.js
,然后再次传递给Touch.js
就像我在下面所做的那样。
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
. 在Event
类中,您将回调绑定到this
。 That is wrong because in this context this
is Event
instance and doesn't contain a
or b
variable. 这是错误的,因为在这种情况下, this
是Event
实例,并且不包含a
或b
变量。 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. 发送回调时,您要将proTouch
绑定到start
方法。 So, bind there. 因此,绑定在那里。
this.Event.register(this.elem, 'mouseenter', proTouch.start.bind(proTouch), this.C);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.