JavaScript "Object Method" - javascript

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.

Related

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.

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?

how to connect a javascript object to a dynamically created html element inside a function

i am making a game in which i want to have a "player" object, and i want to do this in a function, but i also want to bind the object to the image displayed as the player. i want this because i later create monsters, and i want the hover to have a similar effect with a hover, but be based on that object's property's (i.e. display their health). my current method does not use .data(), and employ's backwards coding, while it works fine for what i have now, i cant expand my game with this code so i want to fix it up.
here is my attempt
function Player() {
this.currentLocation = 0;
printPlayer(this);
}
function printPlayer(p) {
$("#" + p.currentLocation).html( "<img src = 'http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png'" +
"class='onTop displayCurrentHealth' alt='you' border='0' />" +
"<div class = 'healthLost hide'></div>");
}
var player = new Player();
console.log($("#" + player.currentLocation).data("inFight", "false"));
console.log($("#" + player.currentLocation).data("inFight"));
console.log($("#" + player.currentLocation).data(!"inFight"));
this is my console.log() result
Object[]
adventure.js (line 62)
null
adventure.js (line 63)
null
adventure.js (line 64)
here is my old code
function Player(id) {
this.id = id;
this.healthid = this.id + "health";
this.displayText = "<img src = 'http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png'" +
"class='onTop displayCurrentHealth' id='" + this.id + "' alt='you' border='0' />" +
"<div id = '" + this.healthid + "' class = 'healthLost hide'></div>";
this.inFight = false;
this.currentLocation = 0;
this.xp = 0;
this.level = 1;
}
Object.defineProperty(player,"health",{
set: function() {
return 100 + ( this.level * 150 );
},
get: function() {
return 100 + ( this.level * 150 );
},
enumerable: true
} );
player.currentHealth = player.health;
Object.defineProperty(player,"strength",{
set: function() {
return ( this.level * 5 );
},
get: function() {
return ( this.level * 5 );
},
enumerable: true
} );
Object.defineProperty(player,"hitRating",{
set: function() {
return 3 + ( this.level );
},
get: function() {
return 3 + ( this.level );
},
enumerable: true
} );
how do i create that as jquery data(), dynamically in a function, onto a image that can have a changing location?
--update--
i added in this
$("#" + player.currentLocation).data("foo");
console.log($("#" + player.currentLocation).data());
which also returns null.
--update--
ok so i take it i need some sort of mvc, is there a way to do this in just javascript/jquery? and if yes how? please provide full explanation and/or links.
As pointed out in the comments, the key to keeping the data is keeping the DOM node it is attached to.
One way to start could look like this (going from your code, making the smallest possible change):
function Player() {
var self = this;
self.location = 0;
self.level = 1;
self.xp = 0;
self.inFight = false;
// add methods that calculate XP and so on
}
function Game() {
var self = this,
player = new Player(),
$playerSprite = $("<img>", {
"class": "onTop displayCurrentHealth",
"src": "http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png",
"alt": "you"
}).data("model", player);
self.printPlayer = function () {
$("#" + player.location).append($playerSprite);
};
// init
self.printPlayer();
}
Don't attach data() to any of your DOM nodes. You should have an object that is aware of it's DOM nodes, as well as a Model. Your monsters can also get access to the Model so they know how much health is left on the player.
It's very rare you'd need to use data() to pass info around. It will make it more difficult to keep your app updated, especially if you want to tweak the DOM later.
Keep your DOM and business logic as separate as possible to keep flexibility up.
var Model = Function( id ) {
this.health = 100;
this.id = id;
};
// This object is showing examples of different ways an object can know about the image
var Monster = Function( hero_model, monster_model ) {
this.sprite = $('#element').tmpl({}); // using jQuery template
this.sprite = $('<img src="">'); // if you are making image based on model data
this.sprite = $('#img-' + hero_model.id ); // if you wanted to look on DOM then, based on data passed in
this.sprite = document.getElementById( 'img-' + hero_model.id ); // to get element without jquery
};
var Player = Function( model ) {
this.model = model;
}
// Passing 1 as ID, but you can have a number that increments
var hero_model = new Model( 1 );
hero_model.damage = 50;
var monster_model = new Model( 1 );
monster_model.damage = 10;
var hero = new Player( hero_model );
var monster = new Monster( hero_model, monster_model );

How to create a new object in JavaScript?

Why is this not working??
var sheep = function(options){
this.options = {sizes: 100,
eat: 100,
colors: 'white',
running: function () {
return this.sizes + this.eat;
}
}
};
var blacksheep = new sheep({colors:'black'});
alert('blackcsheep color is ' + blacksheep.colors);//error undefined
alert('blackcsheep color is ' + blacksheep.options.colors);// it return white
alert('blackcsheep running is ' + blacksheep.running());//error
The syntax:
var sheep = {sizes:100, eat:100, colors:'white',running:function(){
return this.sizes+this.eat;
}
};
is an object literal. It defines an instance of an object, but not the class that defines it. Therefore, there is no way to "new-up" another instance of the object.
Take a look at jQuery's extend functionality:
var blacksheep = {
}
$.extend(blacksheep, sheep, { color: black });
This will copy all the properties of sheep into blacksheep, then merge the third parameter into blacksheep, effectively achieving what you want.
To make another black sheep based on sheep, in this scenario you could do (using jQuery):
var blacksheep = $.extend(sheep, { color: 'black' });
You can create a sheep object like this.
function Sheep(sizes,eat,colors){
this.sizes = sizes;
this.eat = eat;
this.colors = colors;
this.running = function (){
return this.sizes+this.eat;
}
}
Alternatively you can write like this also
function Sheep(sizes,eat,colors){
this.sizes = sizes;
this.eat = eat;
this.colors = colors;
}
sheep.prototype.running = function(){
return this.sizes + this.eat;
}
var sheep1 = new Sheep('100','100','white');
var sheep = function(){
this.sizes = 100;
this.eat = 100;
this.colors = 'white';
this.running = function(){
return this.sizers + this.eat;
}
}
You don't declare objects in JavaScript in the same way as you do in strongly-typed languages. You declare objects by using functions like this:
function sheep() {
this.color = "white";
this.size = 200;
this.speed = 100;
this.running = function () {
return "the sheep is running!";
};
}
var blacksheep = new sheep();
alert('sheep size is ' + blacksheep.size);
alert('sheep running is ' + blacksheep.running());​
Your new object does not work because you are creating a new object with a sub-object called options. options contains all of your methods. As such only the second of these three lines that you gave will give you the correct response:
alert('blackcsheep color is ' + blacksheep.colors);
alert('blackcsheep color is ' + blacksheep.options.colors); // Only this one correctly references `options`.
alert('blackcsheep running is ' + blacksheep.running());
in your case sheep is already an object you can not create object of an object.
you can directly use that object with property.
But i think you want something like this
var sheep = {sizes:100, eat:100, colors:'white', running:function(){
return this.sizes+this.eat;
}
}; Object.defineProperty(sheep, 'colors', { value: 'black'
, writable: true });
Thanks
Javascript is prototype based not class based. It does not use classes and is also object orientated.
var whitesheep =new sheep("100","100","white","running");
var blacksheep =new sheep("100","100","black","running");

Get Next and Previous Elements in JavaScript array

I have a large array, with non-sequential IDs, that looks something like this:
PhotoList[89725] = new Array();
PhotoList[89725]['ImageID'] = '89725';
PhotoList[89725]['ImageSize'] = '123';
PhotoList[89726] = new Array();
PhotoList[89726]['ImageID'] = '89726';
PhotoList[89726]['ImageSize'] = '234';
PhotoList[89727] = new Array();
PhotoList[89727]['ImageID'] = '89727';
PhotoList[89727]['ImageSize'] = '345';
Etc....
I'm trying to figure out, given an ID, how can I can get the next and previous ID... So that I could do something like this:
<div id="current">Showing You ID: 89726 Size: 234</div>
Get Prev Get Next
Obviously, if we're at the end or beginning of the array we just a message...
Why don't you add properties 'Prev' & 'Next' to that array?
PhotoList[89725] = new Array();
PhotoList[89725]['Prev'] = 89724;
PhotoList[89725]['Next'] = 89726;
PhotoList[89725]['ImageID'] = '89725';
PhotoList[89725]['ImageSize'] = '123';
This is just 'doubly-linked list' data structure.
Based on your example the IDs are sequential...
This is another way of writing your example. new Array() really isn't what you should be using because those are objects you are creating. Also, I left the numbers as strings, but I'm not sure why you would want to do that. You could add next and prev like kuy suggested
PhotoList[89725] = {ImageID: '89725',
ImageSize: '123'};
PhotoList[89725] = {ImageID: '89726',
ImageSize: '234',
Next: '89727',
Prev: '89725'};
PhotoList[89725] = {ImageID: '89727',
ImageSize: '345'};
All of these are accessible just like your other structure.
There's really no way other than to iterate through the possible ids sequentially until you find one which has an entry in your array. For example:
function findClosest(arr, id, increasing) {
var step = increasing ? 1 : -1;
for(var i=id+step; i>=0 && i<=max_id; i+=step)
if( arr[id] )
return id;
}
Obviously, this approach requires that you keep track of the max_id so that you don't iterate forever; here I assume that it's a global variable, but you might want to make it a parameter to the findClosest function. You'd call this function like so:
var prev = findClosest(arr, id, false);
var next = findClosest(arr, id, true);
I agree with the rest quotes you should be using objects not an array. Also make sure you create new arrays using the literal notation and not the new keyword with built in types. The new keyword is bad news and you could clobber the global object. Check out JSLint.
var a = new Array(); //bad dont use
var a = []; //this is the best way to create a new array
var o = {}; //create new objects like this
As for the problem at hand. Why not write a simple container that has its own internal counter?
function PhotoListContainer(PhotoList)
{
if(PhotoList === undefined)
throw("no photo list");
this.counter = 0;
var self = this;
this.current = function(){
return PhotoList[self.counter];
};
this.next = function(){
return PhotoList[self.counter + 1];
};
this.prev = function(){
return PhotoList[self.counter - 1];
};
// You could even write a function that loops each value from the current counter :)
this.each_from_counter = function(callback){
for(var i = self.counter; i < PhotoList.length; i++)
{
callback(PhotoList[i], i);
self.counter++;
}
};
}
//use
var pc = new PhotoListContainer(PhotoList);
pc.counter = 500;
pc.next(); //returns the 501st object
pc.prev(); //returns the 499th object
pc.each_from_counter(function(photo, index){
photo.somehting;
});
No arrays at all are better..
images = {
0: {
size: 12345, /* dont realy need as you can use JS to mesure the size. */
title: "day 1 on holiday"
},
1: {
size: 13549, /* dont realy need as you can use JS to mesure the size. */
title: "day 2 on holiday"
},
2: {
size: 16548, /* dont realy need as you can use JS to mesure the size. */
title: "day 3 on holiday"
},
}
for(x in images){
/* x = "the id of the image." */
url[] = "/images/" + x + ".png";
title[] = images[x].title;
size[] = images[x].size;
console.log("File: " + url[x] + " , Title: " + title[x] + " , Size: " + size + "bytes")
}
var sibNum = 0;
var sibList = [];
var prevSiblingID = false;
for (n in w) {
sibNum++;
sibList[n] = {
title : n,
prevSiblingID : prevSiblingID
};
if (prevSiblingID) {
sibList[prevSiblingID].nextSiblingID = n;
}
prevSiblingID = n;
};
sibList[prevSiblingID].nextSiblingID = false;
you can use grep function and calculate prev or next item of specified array:
object = $.grep(data, function(e) {
if(e.id == yourId) {
return data[data.indexOf(e) + 1]; // or -1 for prev item
}
});
i think your image list will come from DB so you may can try this code, this code is working for me.
<?
$prev="";
$next="";
$cur=0;
$i=0;
$pid=$_GET['pid'];
while($rowcon=mysql_fetch_assoc($result))
{
$arr[$i]=$rowcon['pid'];
if($rowcon['pid']==$pid)
{
$cur=$i;
}
$i++;
}
if($cur<$num_rows)
$next=$arr[$cur+1];
else
$next="";
if($cur>0)
$prev=$arr[$cur-1];
else
$prev="";
echo $prev." ".$cur." ".$next;
?>

Categories