Foreign variables display as 'undefined' - javascript

Hello to anyone who will read this post,
I have two standalone javascript files, one of which possesses a class with variables that I would like to use in the other file. We will call the file that possesses the class script.js, and the other file index.js. The code inside index (which is the main file we want to run) compiles fine, but when I run it, my variable prints out as 'undefined'. The variables work fine when they are inside index file themselves, but inside the script.js's class, they are undefined. I would very much like to keep script.js, and keep my variables inside the class. I use an object instance that we will call script obj, and I would very much like to keep my objects. I am not a fan of the static method.
Example: Script.js's class
class script{
constructor(){
var laggies = parseInt(1)
}
}
Above, laggies is defined with a value of 1. Nice, yes? Now let us look at index.js(Just pretend that the object has been initialized)
Example:
console.log(obj.laggies)
This is where I get my problem. I am using repl.it with node version 12.16.1
Thank you for your time.

You are getting the undefined error because the class does not have a variable called laggies. Its defined inside the constructor of the class and not elsewhere.
Try this
class script{
constructor() {
this.laggies = parseInt( 1)
}
}

Related

How to pass object to client using Websockets? (use object class from js file in html script)

In my index.js I have a class
class Digit() {
//construct
add() {
//do whatever
}
}
and
let C = new Digit();
I pass this to the client using
WS.send(JSON.stringify(C))
which is recieved/interpreted in index.html. This all works perfectly and the issue is not with this proccess.
However when I try to use C.add(), I get the TypeError: function add does not exist. In my eyes either the error is that there is no 'context' for the class and thus the methods cannot be accessed, there is some namespace error, or JSON.stringify cannot properly send objects of custom classes. So how do I fix this error?

How do I name an imported module dynamically with javascript eval()?

I want to create a dynamically named variable so that I can use it as a module. I am using eval() to do it, but for some reason it's not working as expected and claiming that the constant I created inside of it doesn't exist.
I have a main folder with this structure:
main
|- commands
|- |- testmod.js
|- test.js
Testmod.js has a simple function export inside of it that logs something to console when run:
function cmd() {
console.log('it worked :)');
}
module.exports = { cmd };
And in test.js, I want to try importing it dynamically:
const foo = 'testmodule';
eval(`const ${foo} = require('./commands/testmod.js');`);
eval(`${foo}.cmd();`)
However, it runs with an error, ReferenceError: testmodule is not defined, and I don't know why.
Expected:
1. define a variable named foo
2. evaluate a string that requires contents of another js file, and name that import as the contents of variable foo
3. evaluate this: a module with name of variable foo and then run the command 'cmd()' inside of it.
expected output: it worked :)
Should I try to find a different method of dynamically naming variables? I'm 99% sure that this method of doing things is unstable and unintended, but if I could get it to work somehow it would be great.
Alright, so my solution was to create an Object, then assign stuff to it. This way, there aren't any new variables and its just an object that can be called later. Thanks Emiel.
const foo = 'testmodule';
let bar = {
foo: require('./commands/testmod.js'),
};
bar.foo.cmd();

What is the proper use of super.call(this)

I have a class function (not originally developed by me)...
function Project()
{
Project.super.call(this);
// this._some_var = null;
/* other initial vars */
...
return DefensiveObject.create(this); // see comment below
}
function initialize()
{
//*******Initialize Project************
}
...
return Project;
This function is part of a module called "Project.js" included by running node main.js.
return DefensiveObject.create(this); // not return Object.create(this)
DefensiveObject is a class to prevent objects from getting or
setting properties that are not explicitly setup in the class.
The main.js calls Project.initialize() which resides within my Project class.
My question is why would there be a need to call "Project.super.call(this);"?
in Javascript the reserved word super is used on ES6 classes for referencing the parent of a child class, it doesn't makes sense to use it referencing a function.
please read this article where the usage of super is explained
https://jordankasper.com/understanding-super-in-javascript/
also this medium article can help you
https://medium.com/beginners-guide-to-mobile-web-development/super-and-extends-in-javascript-es6-understanding-the-tough-parts-6120372d3420
The Project.super.call(this) line was a way to allow use of a dispose method in a "Disposable" class (not included in the original question) which allowed for a clean up of code from memory.

Why is 'this' undefined in the debugger but printable in a console.log?

When setting a breakpoint on the console.log statement, why would this be undefined in the debugger but the statement print with no issues? Am I missing something in regards to scope here?
export class OptionsSidebarComponent {
...
public filters: Object = new Object();
...
public generateFilters() {
for (let property in this.terms) {
if (this.terms.hasOwnProperty(property) && this.terms[property] !== null) {
if (!this.filters.hasOwnProperty(this.productGroup.id)){
this.filters[this.productGroup.id] = new Filters();
}
this.terms[property].forEach((term) => {
console.log(this.filters);
});
}
}
}
}
With typescript While debugging, keep in mind that transpilers can rename variables. Using the original name in the console without sourcemaps that include renaming will show you undefined even if the original value isn't. Make sure you use the transpiled name in watches or console commands.
When you're referencing this with your console.log statement inside its own class, you're using it in its relevant scope. Depending on the framework you are using, different terms are used to reference your class... AngularJS used $scope- Angular 2+ uses this to reference the current class (or current scope/context).
When you use this in your debugger you're using it outside of its scope. It no longer references the class you intend it to.
Each one of your components in Angular uses this to reference itself. Here's an article to explain in further detail: https://angular-2-training-book.rangle.io/handout/features/refresher_on_this.html
If we simplify it to basic javascript and look at your class as just a function a good example would be this:
function example(){
var anything = 10;
console.log(anything); //output: 10
}
console.log(anything); //undefined! we're out of scope :)
So looking at it from this perspective, this is nothing magical. It's just provided to us by Angular to make our references to other things inside our components easier.

Accessing variables and methods from another file

In this case, How do I access the variable and method declared in a file from another file?
File one
jQuery(function(t) {
var myVar = 'myValue',
e = function(t) {
console.log('myLog');
}
});
File two
jQuery(function($){
// ????
});
You don't. It has nothing to do with files (JavaScript largely doesn't care about files unless they're ES2015+ modules), it has to do with the fact that both myVar and e are entirely private to the anonymous function you're passing into jQuery in the first code block. Even other code outside that function in the same file would be unable to access them.
You'd have to change the first file to make that information accessible outside that function. You could do that by making them globals (blech), or by having a single global you use for all of your things like this with an object with properties for these things (slightly less "blech" :-) ), or by using something like Webpack and true modules.
It really depends on how you setup your scripts. For instance:
<script src="fileOne.js"></script>
<script src="fileTwo.js"></script>
Then you will be able to do the following:
File One:
- Declare variable x
File Two:
- Access variable x
I recommend taking a look at this, it'll help with understanding variable scope (however this doesn't cover ES6's let): https://www.w3schools.com/js/js_scope.asp

Categories

Resources