Difficulty getting functions to work in my Javascript class - javascript

Clearly, a new developer! Thank you for replying in advance, I know the answer must be really simple but I have been stuck for an hour.
This exercise asks to create a class and then asks to change some of the dynamic values using class methods/functions. I am not able to get my values to change when I call the function.
Here are the directions for the exercise, followed by my code, sorry that my work looks so rudimentary!
These are the directions:
// Create a new class called SuperHero
// - Your class should have the following DYNAMIC values
// - name
// - superpower
// - age
// - Your class should have the following STATIC values
// - archNemesis, assigned to "The Syntax Error"
// - powerLevel = 100
// - energyLevel = 50
//Where I start having issues is here:
// - Create the following class methods
// - sayName, should print the hero's name to the console
// - maximizeEnergy, should update the energyLevel to 1000
// - gainPower, should take an argument of a number and INCREASE the powerLevel //by that number
class SuperHero {
constructor(name, superpower, age,){
this.name = name;
this.superpower = superpower;
this.age = age;
this.archNemesis = "The Syntax Error";
this.powerLevel = 100;
this.energyLevel = 50;
}
var power = 20;
sayName() {
console.log(this.name);
}
maximizeEnergy() {
this.energyLevel = 1000;
}
gainPower(power) {
this.powerLevel = this.powerLevel + power;
}
};
var superHero1 = new SuperHero("Batman", "strength", 40);
Thanks again! :)

Well, you code is 80% correct. Only issues I see is the this.energyLevel(1000); and sayName() method. They are not really required.
this.energyLevel is a property and not a function, so calling it like this.energyLevel(1000); is wrong. You should be setting this value as this.energyLevel = 1000;
sayName() is not really doing anything useful. You are already setting/initializing the name in the constructor.
Here is a simple example of a class and how to use it's methods for changing it's property values. Check the output in your browser console.
class SuperHero {
constructor(name, superpower, age, archNemesis, powerLevel, energyLevel) {
this.name = name;
this.superpower = superpower;
this.age = age;
this.archNemesis = "The Syntax Error";
this.powerLevel = 100;
this.energyLevel = 50;
}
maximizeEnergy() {
this.energyLevel = 1000;
}
gainPower(gainPower = 20) {
this.powerLevel += gainPower;
}
}
var superHero1 = new SuperHero("Batman", "strength", 40, "The Joker", 100, 50);
var superHero2 = new SuperHero("Wonder Woman", "agility", "Cheetah", 1000, 1000);
console.log('name', superHero1.name);
console.log('superpower',superHero1.superpower);
console.log('archNemesis',superHero1.archNemesis);
console.log('energyLevel',superHero1.energyLevel);
superHero1.gainPower(100);
console.log('powerLevel',superHero1.powerLevel);
console.log('-------------------------------------');
console.log('name', superHero2.name);
console.log('superpower',superHero2.superpower);
console.log('archNemesis',superHero2.archNemesis);
console.log('energyLevel',superHero2.energyLevel);
superHero2.gainPower(200);
console.log('powerLevel',superHero2.powerLevel);

you probably want to do things more like this:
sayName() {
console.log(this.name);
}
maximizeEnergy() {
this.energyLevel = 1000;
}
gainPower(power) {
this.powerLevel = this.powerLevel + power;
}
They are all pretty self explanatory.

Related

Create class with dynamic properties

I create a class for my RPG games, and I would like to ask the user the name of their character, how can I do this ?
Pitch is the base name I created, but I would like pitch to be replaced by the name given by the user
class Personnage {
constructor(nom, sante, force) {
this.nom = nom;
this.sante = sante;
this.force = force;
this.xp = 0;
}
const principal = new Personnage("Pitch", 150, 25);
Thx for your answers ! (sorry for my english aha)
Consider this version to achieve what you are trying.
class Personnage {
var _nom;
var _force;
var _xp;
constructor(nom, sante, force) {
_nom = nom;
_sante = sante;
_force = force;
_xp = 0;
}
const principal = new Personnage(some_user_variable, 150, 25);
Though it is unclear what you are trying to do. Does this help?

Calling a function to change an objects position in an array (JavaScript)

I'm trying to figure out how I can use a function to change the array index value of an object when a function is called and I can't figure out how to do it. Here's what I have so far:
var direction = ["North","East","South","West"];
var car = function() {
/* Class Constructor */
this.cardinal = 0;
this.currentDirection = direction[this.cardinal];
this.showDirection = compass;
this.turnRight = rightTurn;
function compass()
{
document.write("<li>" + this.name + " is going " + this.direction + ".</li>");
}
function rightTurn()
{
if (this.cardinal < 4) {
this.cardinal = this.cardinal + 1;
this.showDirection();
} else {
this.cardinal = 0;
this.showDirection();
}
}
} // end car constructor
pontiac = new car();
Later I call the function buy using this
pontiac.turnRight();
The object does have a bit more to it but I removed that section to make it easier to read. I can add the additional bits if needed but I don't think it's really relevant to this. I know I'm doing the rightTurn() function incorrectly. I used the if else loop because I need it to go back to North if the car is on West (since it's the last position of the array)
Any help is appreciated!
When this.cardinal is 3,
if (this.cardinal < 4) {
this.cardinal = this.cardinal + 1;
lets it become 4, indexing out of the array (valid indices are 0, 1, 2 and 3).
So you need 3 in the comparison:
if (this.cardinal < 3) {
this.cardinal = this.cardinal + 1;
Hope this can help you
var car = function() {
/* Class Constructor */
this.directions = ["North","East","South","West"];
this.currentIndex = 0;
this.showDirection = compass;
this.turnRight = rightTurn;
this.name = "car"
function compass()
{
document.write("<li>" + this.name + " is going " + this.directions[this.currentIndex] + ".</li>");
}
function rightTurn()
{
if (this.currentIndex == (this.directions.length-1)) {
this.currentIndex = 0;
this.showDirection();
} else {
this.currentIndex++;
this.showDirection();
}
}
} // end car constructor
pontiac = new car();
pontiac.turnRight()
every time you call pontiac.turnRight() you will set the current direction to right element beside, and when you get to "west" yo will go back to "North".
Remember that this.direction needs to be this.direction everywhere inside your class. If I were you I'd change the name of your your array from direction to cardinals or something, so you don't confuse yourself.

How can I use composition with methods in ES6 Classes?

I am struggling to implement composition in ES6 classes! I am trying to understand a lot of things at once and have maybe made a stupid error.
I would like to avoid inheritance using extend and super for now, and have found this nice example of composition that seems to show what I am after:
class EmployeeTaxData {
constructor(ssn, salary) {
this.ssn = ssn;
this.salary = salary;
}
// ...
}
class Employee {
constructor(name, email) {
this.name = name;
this.email = email;
}
setTaxData(ssn, salary) {
this.taxData = new EmployeeTaxData(ssn, salary);
}
// ...
}
In regard to the code below, I would like to use the most simple and eloquent way to make the spin() method available for the objects created by the Hero class so it is using a shared prototype. I would like to share this method with other objects that will need it too.
Unfortunately I can't make my code work as the this.angle is not referring to to the Hero class that it needs to, but the Spinner class?
class Spinner {
constructor(direction){
this.direction = direction;
}
spin(direction) {
switch (direction) {
case 'left':
this.angle -= 1;
break;
case 'right':
this.angle += 1;
break;
// no default
}
}
}
class Hero {
constructor(xPosition, yPosition) {
this.description = 'hero';
this.width = 25;
this.height = 50;
this.xPosition = xPosition;
this.yPosition = yPosition;
this.angle = 0;
this.color = 'red';
this.spin = new Spinner();
}
spin() {
this.spin.spin();
}
}
const heroClass = new Hero(100, 200);
console.log(heroClass.angle); // result is 0
heroClass.spin.spin('left');
console.log(heroClass.angle); // result is STILL 0, it didn't work
...the this.angle is not referring to to the Hero class that it needs to, but the Spinner class?
As it should. When you're inside the spinner class, then this refers to a spinner object, which also means this.angle inside the spinner class refers to an angle property of a spinner object.
You'll probably want spinner to return a new angle value, then the hero object that uses spinner should save the returned new angle value.
class Spinner {
constructor(direction){
this.direction = direction;
}
spin(direction, angle) {
switch (direction) {
case 'left':
angle -= 1;
break;
case 'right':
angle += 1;
break;
// no default
}
return angle;
}
}
class Hero {
constructor(xPosition, yPosition) {
this.description = 'hero';
this.width = 25;
this.height = 50;
this.xPosition = xPosition;
this.yPosition = yPosition;
this.angle = 0;
this.color = 'red';
this.spinner = new Spinner();
}
spin(direction) {
this.angle = this.spinner.spin(direction, this.angle);
}
}
const heroClass = new Hero(100, 200);
console.log(heroClass.angle); // result is 0
heroClass.spin('left');
console.log(heroClass.angle); // result is -1
I had to make a few other small changes for this to work. For example, you had a data property named "spin" this.spin = new Spinner as well as a method named spin spin() {. They were overriding one another.

Storing prompt as object value

I am making a game that battles a monster when you click the button and the equation for damage is based on the player and monsters stats. I had help getting the object for the monster to work in the equation but I don't know how to get the Player object working properly because it isn't being stored as a select option.
Here is the post I made earlier, it will be easier to understand my code if you look at the answer here firstOther Post
Here is my current fiddle
I need to be able to prompt the user for their username but still use their stats in the equation.
function Player(username, lvl, exp, gold, hp, atk, def, spd) {
var self = this;
this.username = username;
this.lvl = lvl;
this.exp = exp;
this.gold = gold;
this.hp = hp;
this.atk = atk;
this.def = def;
this.spd = spd;
this.implement = function() {
var h1 = document.getElementById('user');
h1.innerText = this.username;
h1.addClass('playerName');
$(h1).data('player', self)
}
this.implement();
}
var newPlayer = new Player(prompt("What is your username?"), 1, 0, 0, 10, 2, 2, 2);
playerEl = $('.playerName');
player = playerEl.data('player');
You have an error in adding the class playerName, h1 is a dom element reference which does not have the addClass method.
Since you have jQuery, you can use
this.implement = function() {
$('#user').text(this.username).addClass('playerName').data('player', this)
}

Multiple objects aren't getting displayed

I've been messing around with objects in Javascript and I've come across a problem. Basically I'm trying to print certain properties from objects I've created and it's not working properly.
Here's the code:
function Hotel(name, rooms, booked) {
this.name = name;
this.rooms = rooms;
this.booked = booked;
var CanadaHotel = new Hotel("CanadaIn", 50, 10);
var AmericanHotel = new Hotel("AmericanIn", 60, 3);
document.write(CanadaHotel.rooms);
document.write(AmericanHotel.booked);
None of the properties are being displayed and I don't know why.. any help is greatly appreciated.
Thank you
SyntaxError: missing } after function body
Fixed
function Hotel(name, rooms, booked) {
this.name = name;
this.rooms = rooms;
this.booked = booked;
}
var CanadaHotel = new Hotel("CanadaIn", 50, 10);
var AmericanHotel = new Hotel("AmericanIn", 60, 3);
console.log(CanadaHotel.rooms);
console.log(AmericanHotel.booked);

Categories

Resources