Javascript creating methods - how to output - javascript

I am looking for some guidance on the simplest way to create an output for the following code below. Just simple user output into an HTML document. Any guidance would be helpful. Also any guidance on how to use the join method so I could link two properties such as Lname and accNo also?
The idea would be to have user input box (for deposit/withdraw) and then using a button/buttons to complete the function and display the results.
<script>
function Account(fname, lname, accNo, amount) {
this.fname = fname;
this.lname = lname;
this.accNo = accNo;
this.balance = amount;
this.bankDeposit = deposit;
this.bankWithdraw = withdraw;
}
function deposit(amount) {
this.balance += amount;
}
function withdraw(amount) {
if (amount <= this.balance) {
this.balance -= amount;
}
if (amount > this.balance) {
alert("Declined");
}
}
function joinName() {
}
var P1 = new Account("Nathan", "Smith", "SA001", 500);
var P2 = new Account("John", "Smith", "SA002", 1500);
</script>
</body>
</html>

First of all I have to point out that your methods wont work out as is. They need to be declared on your Account class prototype.
Account.prototype.deposit = function(amt) {
...
}
For the issue that you want to output html the absolute easiest method would be
Account.prototype.print = function() {
document.body.innerHTML = JSON.stringify(this);
}
For the issue of combining properties you would do
Account.prototype.joinName = function() {
return this.fname + ‘ ‘ + this.lname;
}
However, if you plan to use that joined name a lot I would just set it in the constructor.
this.joinedName = fname + ‘ ‘ + lname

Related

Passing two variables from function

I'm trying to accomplish three functions, where one gets two values from HTML-elements, one counts exponent of these values and one console.logs what the values used were and the result.
What way would function noudaArvo be able to pass both variables to other functions? I'm trying not to change other two functions.
function laskuFunktio() { //does the printing
var luku = noudaArvo("luku");
var eksp = noudaArvo("eksponentti");
console.log("Luku " + luku + " potenssiin " + eksp + " on:");
console.log(laskePotenssi(luku, eksp));
}
function noudaArvo() { //gets the values, but can't figure how to pass them out
let luku = document.getElementById("luku").value;
let eksponentti = document.getElementById("eksponentti").value;
}
function laskePotenssi() { //counts the exponent
var luku = noudaArvo("luku");
var eksponentti = noudaArvo("eksponentti");
return Math.pow(luku, eksponentti);
}
function laskuFunktio() { //does the printing
var luku = noudaArvo("luku");
var eksp = noudaArvo("eksponentti");
console.log("Luku " + luku + " potenssiin " + eksp + " on:");
console.log(laskePotenssi(luku, eksp));
}
function noudaArvo(item) { //gets the values, but can't figure how to pass them out
return document.getElementById(item).value;
}
function laskePotenssi(luku, eksp) { //counts the exponent
return Math.pow(luku, eksp);
}
If I understand what your saying correctly this may be a solution to your problem
U don't return from noudaArvo function anything
change the function to
function noudaArvo(elId) { //gets the values, but can't figure how to pass them out
return document.getElementById(elId).value;
}

JavaScript localStorage: how to parse method from saved array object using JSON.stringify

I have the following JavaScript code:
function Product(){
this.ProductName="";
this.Quantity=0;
this.Price=0;
this.Category="";
this.Total=function() {
return this.Quantity * this.Price;
}
this.Discount=function() {
return this.Total() * 0.25;
}
}
var Product = new Product();
Product.ProductName="Tipkovnica";
Product.Quantity=100;
Product.Price=150.5;
Product.Category="IT";
if(localStorage.Products){
Products = JSON.parse(localStorage.getItem("Products"));
}
else
{
var Products = [];
}
Products.push(Product);
localStorage.setItem('Products', JSON.stringify(Products));
function RetrieveObjects(Products){
for(var a=0;a<Products.length; a++){
document.write("<br>Product Name: "+Products[a].ProductName);
document.write("<br>Quantity: "+Products[a].Quantity);
document.write("<br>Price: "+Products[a].Price);
document.write("<br>Category: "+Products[a].Category);
document.write("<br>Total: "+Products[a].Total());
document.write("<br>Discount: "+Products[a].Discount());
}
}
I made JSON.stringify to store array object in JSON.
Then, When I tried to loop object from array back from storage after JSON parse, I got error because methods Total() and Discount() were not recognized as methods.
Any idea why?
Thanks,
Milan
Your function is using this but that is the global this which is the window object.
However, there is another problem, you cannot (or rather should not) store functions in JSON as there is no function data type. You should calculate the values and store the result in your JSON.
var Product {
productName: null,
quantity: 0,
price: 0,
category: null,
finalTotal: 0,
discountedTotal: 0,
total: function() {
return this.quantity * this.price;
},
discount: function() {
return this.total() * 0.25;
}
}
var newProduct = Object.create(Product);
newProduct.productName = "Tipkovnica";
newProduct.quantity = 100;
newProduct.price = 150.5;
newProduct.category = "IT";
newProduct.finalTotal = newProduct.total();
newProduct.discountedTotal = newProduct.discount();
if (localStorage.Products) {
Products = JSON.parse(localStorage.getItem("Products"));
Products.push(newProduct);
} else {
Products = [newProduct];
}
localStorage.setItem('Products', JSON.stringify(Products));
function RetrieveObjects(Products) {
for (var a = 0; a < Products.length; a++) {
document.write("<br>Product Name: " + Products[a].productName);
document.write("<br>Quantity: " + Products[a].quantity);
document.write("<br>Price: " + Products[a].price);
document.write("<br>Category: " + Products[a].category);
document.write("<br>Total: " + Products[a].finalTotal);
document.write("<br>Discount: " + Products[a].discountedTotal);
}
}
Because if you stringify the object, then all the methods are removed. Take a look at this: https://stackblitz.com/edit/typescript-2tfnkr
Not related hint: use the camelCase instead of PascalCase convention for all of the methods, properties and variables. PascalCase should be used in class names, interfaces etc.

JavaScript beginner: why does this not work?

My html page is not responding to this code I wrote in JS, i'm a total beginner, and just started learning JS, can somebody tell me why this doesn't work?
/* this is a practice file that'll play with js
nothing strange to look at here folks! */
var firstName = 'Steven';
var lastName = 'Curry';
var fullName = firstName + ' ' + lastName;
function Hotel(HotelName){
this.HotelName = HotelName;
this.numRooms = 20;
this.numGuests;
this.checkAvailability {
if(numRooms != 20 ){
return true;
}
else{
return false;
}
}
this.getHotelName = function(){
//can it work with this dot operator?
return this.HotelName;
}
}
var HiltonHotel = new Hotel('Hilton');
var hName = document.getElementById('hotelName');
hName.textContent = getHotelName();
var el = document.getElementById('name');
el.textContent = fullName;
<!DOCTYPE html>
<html>
<body>
<div id = 'greeting'> Hello
<span id="name">friend</span>!
<h1>Welcome To the <span id = 'hotelName'>Hyatt</span>
</div>
<script
src = "https://stacksnippets.net/js">
</script>
</body>
</html
I'm pretty sure it's ordering and my syntax i need to work on, any advice is greatly appreciated thank you!
Few misunderstandings:
checkAvailability is a function, you are missing parens.
while accessing the getHotelName function, you have to refer to the HiltonHotel variable, to be able to access and call that function.
few minor errors in your html code, while operating in code snippet, you don't have to add a separate script, it's connected together by default.
var firstName = 'Steven';
var lastName = 'Curry';
var fullName = firstName + ' ' + lastName;
function Hotel(HotelName) {
this.HotelName = HotelName;
this.numRooms = 20;
this.numGuests;
this.checkAvailability = function() { // it's a function (missing parens)
if (numRooms != 20) {
return true;
} else {
return false;
}
}
this.getHotelName = function() {
return this.HotelName;
}
}
var WeiHotel = new Hotel('Hilton');
var hName = document.getElementById('hotelName');
hName.textContent = WeiHotel.getHotelName(); // refer to the `WeiHotel` variable
var el = document.getElementById('name');
el.textContent = fullName;
<div id='greeting'> Hello
<span id="name">friend</span>!
<h1>Welcome To the <span id='hotelName'>Hyatt</span></h1>
</div>
An extension to the answer of #KindUser:
You're not using closures anywhere in this class to store some private state. Therefore you should attach the methods to the prototype and not to the instance itself. It's more economic, because now all instances share one function, not one per instance. And the JS engine can optimize that better.
Then, you have another error in checkAvailability: numRooms needs to be addressed as this.numRooms because it is a property of this instance, and there is no variable with this name.
And one about style. If you have something like
if(condition){
return true;
}else{
return false;
}
you can simplify this to:
return condition;
//or if you want to enforce a Boolean value,
//but your condition may return only a truthy/falsy value:
return Boolean(condition);
//sometimes also written as:
return !!(condition);
Next. Stick to the coding standards. In JS a variable/property starting with an uppercase letter would indicate a class/constructor, therefore HotelName, HiltonHotel, WeiHotel are misleading.
And I find the property name hotelName redundant and counter-intuitive. Imo you have a Hotel, it has a name, but that's just an opinion.
var firstName = 'Steven';
var lastName = 'Curry';
var fullName = firstName + ' ' + lastName;
function Hotel(name) {
this.name = name;
this.numRooms = 20;
this.numGuests;
}
Hotel.prototype.checkAvailability = function() {
return this.numRooms !== 20;
}
Hotel.prototype.getHotelName = function() {
return this.name;
}
var hotel = new Hotel('Hilton');
var hName = document.getElementById('hotelName');
hName.textContent = hotel.getHotelName(); // refer to the `weiHotel` variable
var el = document.getElementById('name');
el.textContent = fullName;
<div id='greeting'> Hello
<span id="name">friend</span>!
<h1>Welcome To the <span id='hotelName'>Hyatt</span></h1>
</div>
or as an ES6 class (and some playin around):
class Person{
constructor(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
//this is a getter, you can read it like a property
get fullName(){
return this.firstName + " " + this.lastName;
}
//this function is implicitely called whenever you try to convert
//an instance of `Person` into a string.
toString(){
return this.fullName;
}
}
class Hotel{
constructor(name) {
this.name = name;
this.numRooms = 20;
this.numGuests;
}
checkAvailability() {
return this.numRooms !== 20;
}
getHotelName() {
return this.name;
}
}
var steve = new Person('Steven', 'Curry');
var hotel = new Hotel('Hilton');
var hName = document.getElementById('hotelName');
hName.textContent = hotel.getHotelName(); // refer to the `weiHotel` variable
var el = document.getElementById('name');
el.textContent = steve.fullName;
//this uses the `toString()` method to convert the `Person` steve into a string
//for people, this makes sense, for the Hotel you'd want to think:
// - where do I want to use this?
// - and what should this string contain?
console.log("Hello, I'm " + steve + " and I'm at the "+ hotel.name);
<div id='greeting'> Hello
<span id="name">friend</span>!
<h1>Welcome To the <span id='hotelName'>Hyatt</span></h1>
</div>

trying to reach function inside a class javascript

Good evening, If someone could help me , I would be glad.I am trying to reach some functions in my Car class. Firstly I am trying to assign inpSpeed input value to Car class function Drive and then I wanna print out to console all cars info when I press the button: btnRace and the problem is I dont really know how to call them , because everytime I call them it says:"undefined".
here is my code so far:
carsArray = [];
btnCarName.onclick = function(){
carsArray.push({/*obj.element1, obj.element2, obj.element3*/});
}
btnRace.onclick = function(){
for(j in carsArray)
{
console.log(Car(carsArray[j]));
}
}
function Car(name,speed)
{
this.carBrand = name;
this.speed = speed;
this.distance = 0;
this.Drive = function(time)
{
if(time > 0)
return this.distance = (this.speed * (time/10));
}
this.printData = function()
{
for(var i = 0; i < Car.length; i++)
{
console.log('Car brand: ' + this.carBrand);
console.log('Speed: ' + this.speed);
console.log('distance: ' + this.Drive());
console.log('---------------------------');
}
}
}
For the this keyword to work, you must instantiate Car() with the new keyword:
var toyota = new Car('toyota', 100)
console.log(toyota.speed);
There may however be a couple other issues. What exactly is expected from Car.length?

JavaScript "Object Method"

function Money(bill, accu, hb, food, webHosting, lynda) {
Money.bill = bill;
Money.accu = accu;
Money.hb = hb;
Money.food = food;
Money.webHosting = webHosting;
Money.lynda = lynda;
Money.total = function () {
(Money.bill + Money.accu + Money.hb + Money.food + Money.webHosting + Money.lynda)
return Money.total;
};
}
var cost = new Money(2500, 5000, 2000, 6000, 1000, 30000);
Money.total();
I have defined everything for a object using a variable at the end.
When I run Money.total(the "money" objects method) it returns as ""function""
Please help.I want the total of everything.
You need to use this instead of `Money' to read/write properties of the newly created object:
function Money(bill, accu, hb, food, webHosting, lynda) {
this.bill = bill;
this.accu = accu;
this.hb = hb;
this.food = food;
this.webHosting = webHosting;
this.lynda = lynda;
this.total = function() {
return this.bill + this.accu + this.hb + this.food + this.webHosting + this.lynda;
}
}
It's unclear what you were trying to do with your 'total' method. If you can describe what that is supposed to do, then we could help with that implementation, but I've provided an implementation that sums the properties.

Categories