L
L
lightalex2020-05-03 12:29:53
JavaScript
lightalex, 2020-05-03 12:29:53

How to set variables in scope for a new instance of a class?

Greetings!

There is a class in the file A.js:

class A {
  do() {
    console.log(some_var);
  }
}
module.exports = A;


There is a main file index.js:
const A = require('./A');
function print_it(param) {
  let some_var = param;
  let a = new A;
  a.do();
}
print_it('wow'); // В консоли должно вывестись: wow
print_it('123'); // В консоли должно вывестись: 123


Is it possible to somehow modify index.jswithout changing in A.jsso that some_var becomes readable?
Because now, of course, if this is all run, the error "some_var is not defined" pops up.
Is it possible in JS?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2020-05-03
@lightalex

do not invent a rake, but do it in a simple way:

// A.js
class A {
  constructor(some_var) {
    this.some_var = some_var;
  }

  do() {
    console.log(this.some_var);
  }
}
module.exports = A;

// index.js
const A = require('./A');
function print_it(param) {
  const a = new A(param);
  a.do();
}
print_it('wow'); // В консоли должно вывестись: wow
print_it('123'); // В консоли должно вывестись: 123

PS snake_case is not accepted in js, it is recommended to use camelCase
UPD:
You will have to hack the node module system. You can read it in off-doc:
https://nodejs.org/dist/latest-v14.x/docs/api/modu...
https://nodejs.org/dist/latest-v14.x/docs/api/ vm.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question