Class syntax cannot access variable properly in Javascript - javascript

I'm learning the class syntax in javascript. I'm trying to define a class, which holds a person's first and last name, tardies and absence count. The tardies and the absences are automatically set to 0 on instance initialization. Below is my code with a function that adds tardies and prints the amount of tarides:
class Student{
construtor(firstName,secondName){
this.firstName=firstName;
this.secondName=secondName;
this.tardies=0;
this.absences=0;
}
IncreaseTardies () {
this.tardies+=1
return this.tardies;
}
}
//Test
let Sample = new Student("A","B");
//Output undefined
Sample.IncreaseTardies()
//Output NaN
//Expected output 1
The code doesn't seem to work as intended since it returns NaN instead of the value+1 when IncreaseTardies() is called. I tried placing a console.log inside the constructor, which gave no result at all and adding breakpoints with identical success. What is the error in my code that prevents it from increasing the number of tardies?

The issue was a typo in the constructor function as a name. Thanks to jonrsharpe for pointing out the issue.
The working code is:
class Student{
constructor(firstName,secondName){
this.firstName=firstName;
this.secondName=secondName;
this.tardies=0;
this.absences=0;
}
IncreaseTardies () {
this.tardies+=1
return this.tardies;
}
}

Spelling of constructor is not correct, Please change it to constructor from construtor, Here c is missing... :)

Related

i need to increment a number in a classList template string javascript

hello friends I got a hard one and I'm a bit in a pickle
in my blackjack game I create images(of the cards) and the values come from the .PNG name from a list in an object. what I want to do is be able to create a class on those images to be able to use the classList.contain() method in a other function. it seems to work but the number doesn't increment every time I call the function. All the cards have the same class.
function showCard(activePlayer, card) {
if (activePlayer.score <= 20){
let cardImage = document.createElement("img")
function incrementNumber(number){
number = number++
return number
}
//increment the number of the class
cardImage.classList.add(`images${incrementNumber()}`)
cardImage.src = `images/${card}.png`
document.querySelector(activePlayer["div"]).appendChild(cardImage)
hitSound.play()
}
}
I know i most likely forgot a simple thing but i cannot put my finger on it.
I added a number in the ${incrementNumber(1)} still keeps giving me the same images class for all images. thank you for all you're help!
The ++ (increment) operator can be confusing sometimes.
In your case, you are using it, but you are also assigning its return value back to the number. The easiest solution is not doing that assignment (changing number = number++ for just number++)
It also looks like number should be a global variable, not a parameter passed to the incrementNumber function.
The more interesting part to the problem though, is why the code does not work. This is due to how the ++ operator works. When you place it after a variable name (eg number++) JavaScript will effectively do this:
var temp = number;
number = number + 1;
return temp;
It increments the number variable by 1, but it returns the previous value of the variable. In your case, when assigning the result of number++ back to number, the increment operation will basically be cancelled out.
Also, note that you can place the ++ operator before a variable name (like ++number). This will not return the original value of the variable, instead returning the new (incremented) value.
Add a global variable to your scope named number and set it to one. Then replace number = number++ with number++.

Meteor cursor.fetch().property returns "undefined"

I have a simple helper that returns an array to an #each block inside my template. This works ok and the tags are displaying.
However, i don't understand why i can't console.log a property of the userTags, for instance userTags.BusinessContact. But i can console.log the complete object so (console.log(userTags)) will work.
Template.profileTags.helpers({
tag:function(){
var userTags = tikiUser.find({}).fetch()
//this returns "undefined" 2 times
Meteor.setTimeout(function(){console.log(userTags.BusinessContact)}, 500)
return userTags
}
})
Why is that?
thx,
You are trying to get the BusinessContact property of an array - try doing
userTags[0].BusinessContact
PS: Try to make a meteorpad.com when posting a problem
Just try this.
if(userTags)
{
Console.log(userTags.BusinessContact)
}
In meteor some time we will not get value for the first time so,If we write a if condition than it will check the value there Only.
Hope this helps you.

Javascript - getElementByID - Error

I am getting this error message in my Javascript.
Unable to get property 'style' of undefined or null reference
document.getElementById('BS2').style.display='block';
What is going on it that sometimes the Element ID is not showing. Is there a way to check if the element is there then do this else, go to the next line of code?
function showb() {
if(document.getElementById('BS1').style.display=='none') {
document.getElementById('BS1').style.display='block';
document.getElementById('BS2').style.display='block';
document.getElementById('BS3').style.display='block';
document.getElementById('BS4').style.display='block';
}
return false;
}
Sometimes the BS1 is showing, BS3 is Showing and BS4... etc.
document.getElementById() returns an object just like anything else. You can assign it to a variable and check the null-ness of the variable:
var bs1 = document.getElementById('BS1');
if (bs1) {
.. do stuff if bs1 is present
} else {
.. do stuff if bs1 is not there
}
AS pointy said in his comment, you should chekc whether there is an element with the desired ID before trying to read its properties. You could use a piece of code like this:
var element = document.getElementById('BS2'); // or any other ID
if (element) { // if no element is found, this evaluates as a logical false.
element.style.display='block';
}
Getting the element in a variable also has the advantage that your code becomes more readable. And since you use this multiple times, you could create a function to encapsulate that logic. Good luck!
Well if the property style hasn't been modified it means that it is just ("")
function showb() {
if(document.getElementById('BS1').style.display) {
document.getElementById('BS1').style.display='block';
document.getElementById('BS2').style.display='block';
document.getElementById('BS3').style.display='block';
document.getElementById('BS4').style.display='block';
}
return false;
}
it is going to be solved just like that because ("") is a falsy value

Apply function javascript looping extra

I'm a newbie to Javascript and created a sample function to test the apply function of the javascript.
I need couple of clarification on this code,
value -x will take the first array ['val1','val2'] but just wondering it substitutes to (this,x)..
2.I see a 3 items being printed in the console.log, the last item being - undefined, undefined, What that happends
var dummyfunction1 = function(val1,val2){
console.log(array1,array2);
};
[['val1','val2'],['val3','val4']].forEach(function(x){
dummyfunction1.apply(this,x);
});
dummyfunction1()
There are a couple of issues here.
dummyfunction1 is using variable that are undefined in the body. It should be this:
var dummyfunction1 = function(val1,val2){
console.log(val1,val2);
};
The last line dummyfunction1() is making an additional call to the dummyfunction1 with no parameters. This is the undefined undefined you are seeing.
The full code should be this:
var dummyfunction1 = function(val1,val2){
console.log(val1,val2);
};
// this will automatically be run, no need to call dummyfunction1 on your own after this
[['val1','val2'],['val3','val4']].forEach(function(x){
dummyfunction1.apply(this,x);
});

Titanium Javascript: "that." does not work

Neither this nor that works. Does anyone know what is going on??
Edit:
qwerty is simply called as "qwerty();" when in other pieces of code.
It is supposed to be indepedent.
Edit: I realize what is wrong. The problem lies with the i...
function qwerty () {
..... for loop that changes i ......
var that = this;
this.chara[i] = createlabel.....
this.chara[i].addEventListener('click', function(e) {
var j = e.source.id;
alert("hello word");
alert(this.chara[j].width); // I get the error here
});
this.chara[i].addEventListener('doubleclick', function(e) {
alert("hello word");
alert(that.chara[i].width); // I get the error here too.
});
}
Any JS problem relating to this is likely due to the way the function using this is called. Storing a reference to this in your that variable should let you reference it from within your nested functions, exactly the way you are doing it already - assuming that qwerty() is called in a way that sets this to the correct object in the first place. (Personally I like to call such a variable self since it more accurately reflects what the variable is doing.)
However, in your function you say you get the error on this line:
that.chara[i].width
Given that you say this.chara[i].addEventListener(...) I'm guessing that the chara[i] variable holds a reference to a DOM element. If that is the case I'm guessing it is an element type that doesn't have a width property. Try this:
that.chara[i].style.width
https://developer.mozilla.org/en/CSS/width
That's the best I can do for you without more information about what error you're getting and how the qwerty() function is called...

Categories

Resources