Reputation: 1224
I am learning node and have created a custom module.
My custom module simple defines a class with a single method.
I would like to be able to call this method once from the defined class object.
I would also like to be able to reference a variable in my main code from this class method.
In the "open" method I have two console.log commands. With the 2nd producing an error "ReferenceError: thisVar is not defined". If I comment out the 2nd console.log that relates to the error "open" is printed.
How can I reference thisVar from the class method?
Edit1 I understand from the responses that "thisVar" is outside of the scope of the class and therefor unavailable. With this being the case why does "thatVar" work as it is also defined outside of the class? Is the scope relative to the module and not the class?
This is my main js code:
"use strict";
const Door = require('door');
const mydoor = new Door("green");
var thisVar = 1;
console.log(mydoor.colour);
mydoor.open();
This is my "door" module:
"use strict";
var thatVar = 2;
class Door {
constructor(colour) {
this.colour = colour;
}
open() {
console.log("open");
//console.log(thisVar);
console.log(thatVar);
}
}
module.exports = Door;
Upvotes: 0
Views: 45
Reputation: 59916
Door.js
// Door.js
'use strict';
module.exports = class Door {
constructor(colour) {
this.colour = colour;
}
open(ThisVar) {
console.log("open");
if(ThisVar)
console.log(ThisVar);
}
}
main.js
'use strict';
var Door = require('./Door.js');
var someone = new Door("pink");
var a=7;
someone.open(a);
someone.open();
Upvotes: 1
Reputation: 833
thisVar
is not in the scope of the door
module. The Door
somehow needs to access to thisVar
, so I would pass to the constructor.
class Door {
constructor(colour, thisVar) {
this.colour = colour;
this.thisVar = thisVar;
}
open() {
console.log('open');
console.log(thisVar);
}
}
module.exports = Door;
Main js:
const door = require('door');
const myDorr = new Door('green', 1);
Upvotes: 1