There are two properties for my bike method.front gear and rear gear.i want another property which will be a new property called gear ratio property which can be obtained by multiplying front and rear gear numbers.the code i have written giving continuous error.how it can be fixed.
function write() {
var bicycle = {
price: 20000,
model: "raleigh",
front_gear: 3,
rear_gear: 7,
gear_ratio: function () {
ratio: this.front_gear * this.rear_gear,
}
}
document.write("this is a " + bicycle.gear_ratio.ratio + " speed bike");
}
window.onload = write;
gear_ratio: function () {
return this.front_gear * this.rear_gear
}
document.write("this is a " + bicycle.gear_ratio() + " speed bike");
Is about the best I can recommend you do. If you still want an object:
gear_ratio: function () {
return {
ratio: this.front_gear * this.rear_gear
}
}
document.write("this is a " + bicycle.gear_ratio().ratio + " speed bike");
It is possible to write something like:
function bike(settings){
// Make settings an object so we can use it always
if (typeof settings != 'object')
settings = {}
// if settings has a price use that, otherwise use 0
this.price = settings.price || 500;
this.model = settings.model || "custom";
this.front_gear = settings.front_gear || 2;
this.rear_gear = settings.rear_gear || 2;
this.__defineGetter__("gear_ratio", function(){
return this.front_gear * this.rear_gear;
});
}
function write() {
var bike1 = new bike({
price: 20000,
model: "raleigh",
front_gear: 3,
rear_gear: 7,
});
var bike2 = new bike({
front_gear: 3,
});
document.write("<br /> bike 1 is a " + bike1.gear_ratio + " speed bike by " + bike1.model + " costing " + bike1.price);
document.write("<br /> bike 2 is a " + bike2.gear_ratio + " speed bike by " + bike2.model + " costing " + bike1.price);
}
Where the function call is implied, however this will require your bike to be an actual instantiated class, and won't work in every browser and is harder to debug. Let me know if you want a better explanation.
change this
window.onload = write;
to this
window.onload = write();
you're calling the function in an inappropriate way
Related
So i've recently ran into issues with trying to move specific pieces of a <p> </p> called result. as such i thought hey! wouldn't be easier to break each part inside of result down into another <p>!? well it works lol however trying to grab that inner <p> that in this cause we'll call vault is being difficult. I've tried several methods but cant seem to grab it's value from outside in a document.getElementByID....here's the code below for the html.
document.getElementById("result").innerHTML = Monster + "<p id='vault'> || HP: " + HP + "</p> || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
}
then the script that eventually calls it
function Combat(id){
document.getElementById("vault").innerHTML = id;
document.getElementById("C").value = id
}
So what i'm trying is change id "C" to ID"VAULT" inside of id ("result").
any ideas on why i can't grab vault?
What you want would be easier with Object-oriented JavaScript.
Usually when coding JavaScript you want to be as independent of the DOM (HTML) as possible.
Consider the following example:
/**
* Monster
*/
var Monster = (function() {
function Monster(HP, DEF, ATK, DB, RET, INT, MEXP) {
if (HP === void 0) {
HP = 100;
}
if (DEF === void 0) {
DEF = 10;
}
if (ATK === void 0) {
ATK = 100;
}
if (DB === void 0) {
DB = 10;
}
if (RET === void 0) {
RET = true;
}
if (INT === void 0) {
INT = 100;
}
if (MEXP === void 0) {
MEXP = 100;
}
this.HP = HP;
this.DEF = DEF;
this.ATK = ATK;
this.DB = DB;
this.RET = RET;
this.INT = INT;
this.MEXP = MEXP;
}
/**
* getHTML
*/
Monster.prototype.getHTML = function() {
return "HP: " + this.HP + " || Defense: " + this.DEF + " || Attack: " + this.ATK + " || Can it Dodge/Block: " + this.DB + " || Can it retaliate: " + this.RET + " || Initative: " + this.INT + " || Exp: " + this.MEXP;
};
/**
* attacked
*/
Monster.prototype.attacked = function(damage) {
if (damage === void 0) {
damage = 0;
}
//check defences
if (damage > this.DEF + this.DB) {
//take damage
this.HP -= (damage - this.DEF + this.DB);
}
if (this.HP < 0) {
//Return true if it slew the monster
return true;
} else {
//Return false if the monster survived
return false;
}
};
return Monster;
}());
/**
* Area
*/
var Area = (function() {
function Area(name) {
if (name === void 0) {
name = "Vault";
}
this.name = name;
this.monsters = [];
}
/**
* addMonster
*/
Area.prototype.addMonster = function(monster) {
this.monsters.push(monster);
return this;
};
/**
* attackVault
*/
Area.prototype.assault = function(damage) {
if (damage === void 0) {
damage = 0;
}
//If no monster
if (this.monsters.length < 1) {
alert("You have cleared this vault");
return true;
} else {
//If monsters exists, attack the first
var monsterKilled = this.monsters[0].attacked(damage);
//If the monster was killed
if (monsterKilled) {
//remove monster
this.monsters.splice(0, 1);
//Alert the player
alert("Well done hero!\nOnly " + (this.monsters.length) + " remaining!");
}
}
//Return maybe monsters left?
return this.monsters.length < 1;
};
return Area;
}());
////GRAP HTML ELEMENT
var output = document.getElementById("current-monster");
////RUNNING YOUR GAME
//Build and populate world
var vault = new Area();
vault
.addMonster(new Monster())
.addMonster(new Monster());
//INTERACTION
alert("Start");
//Hit the vault till it is empty
while (vault.assault(45) != true) {
output.innerHTML = vault.monsters[0].getHTML();
alert("Attack!");
}
output.innerHTML = "Victory!";
<h1 id="title">Monster Game!</h1>
<h2 id="current-monster"></h2>
See how i can easily access the data though JavaScript?
When coding a JavaScript game, it makes sense to keep important data and structures in your JavaScript.
Ok so i added the bit - ADyson suggested...
document.getElementById("result").innerHTML = Monster + "<p id='vault(" + loop + ")'> || HP: " + HP + "</p>" + " || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
}
}
}
function Chest(id){
window.open('LootGen.html', '_blank');
}
function Combat(id){
var id = document.getElementById("vault" + id).innerHTML;
document.getElementById("C").value = id;
submit();
}
However now when i run it on the " ).innerHTML;" i'm getting a
MonsterGen.html:426 Uncaught TypeError: Cannot read property
'innerHTML' of nullCombat # MonsterGen.html:426onclick #
MonsterGen.html:1
Ok I found out exactly was was going wrong; it was the naming convention in the <P>.
Originally it was id='vault(" + loop + ")'... this would make it vault(1) etc.... however the getElement was getting it by this call ("vault" + id) so it would call vault1....thus two separate id's entirely....that's why it was returning null.
So I removed the () in the equation and now everything is working beautifully.
I am a Javascript learner. I am practicing Javscript object properties and methods.
I want to add another offer to Black pen suppose it will be "10%", how should I go further. Please help.
Is this the correct way of writing code?
function pen(color, size, price) {
this.color = color;
this.size = size;
this.price = price;
}
var pen1 = new pen("Red", "Medium", 20);
var pen2 = new pen("Black", "Large", 35);
var pen3 = new pen("Pink", "Small", 20);
pen.prototype.offer = function() {
return "12%";
}
console.log("You have choosen " + pen1.color + " pen with " + pen1.size + " size. And its price is Rs." + pen1.price);
console.log("You have choosen " + pen2.color + " pen with " + pen2.size + " size. And its price is Rs." + pen2.price);
console.log("You have choosen " + pen3.color + " pen with " + pen3.size + " size. And its price is Rs." + pen3.price + " with " + pen3.offer() + " offer");
You can modify pen2 offer function
pen2.offer = function(){ return parseInt(pen.prototype.offer()) + 10 +"%" ; }
Probably by now you have already got your answer.Here is just another way to explore the prototype
Let use assume that pen is a stationary item.A stationary item can also be a book , a ruler ,a scale and so on.So it is safe to assume that stationary can be a parent object
And pen,ruler,book etc can be child of stationary. & child object can inherit properties.In javascript it is prototype based inheritance.
function Stationary(){
//See there is no options provided here
}
// Adding showItem & offers method to Stationary prototype property
Stationary.prototype.showItem = function(){
console.log("You have choosen " +this.item +" with " +this.color + " having "+ this.size + " size "+". And its price is Rs."
+ this.price +" with "+this.offers(this.offer) +" offer");
}
Stationary.prototype.offers = function(offer){
if(offer){
return offer;
}
else{
return "No offer";
}
}
// Creating an object with some property
var _p1Options ={
item:"Pen",
color:"Indigo",
size:"Large",
price:25,
offer:'12%'
}
//Creating a function which will accept the options
function Item (options){
this.item = options.item || "default";
this.color = options.color || "default";
this.price = options.price || "default";
this.size = options.size || "default";
this.offer = options.offer || "default";
}
//Setting Item's prototype to Stationary's constructor
// It will allow us to inherit all the properties
Item.prototype = new Stationary();
//Create a _p1 object with Item constructor
var _p1 = new Item(_p1Options);
//Item does not have showItem property,it will inherit from Stationary
console.log(_p1.showItem());
So to answer your question you can just create an object like _p1Options & assign property values(including offer) you want instead of hard coding the return value.
Check this jsfiddle for more
First time asking!
my refactored methods (methods used to be inside object) are not recognizing their relations to the object anymore... How do I get these to work?
I'm trying to apply a move and accelerate function to this object (car). The move_fn increases the car's position linearly (1, 2, 3, 4... n). The acc_fn increases the car's acceleration exponentially by adding the car's previous speed increase with its current position (30mph + 2 position = 32mph, 32mph + 3 position = 35mph, 35mph + 4 position = 39mph, etc.). Also, function_runner runs both methods simultaneously, which keeps everything commencing in order:
var move_fn = function(){
var prev_position = this.position
this.position += + 1
console.log(this.type + " is moving from " + prev_position + " to " +
this.position + '.')
}
var spd_fn = function(){
var prev_speed = this.speed
console.log(this.position)
this.speed += this.position
console.log(this.type + ' is accelerating from ' + prev_speed + ' to ' +
this.speed + '.' )
}
var function_runner = function(){
this.move_fn()
this.acc_fn()
}
var car = {
type: 'Honda CRV',
position: 1,
speed: 30,
move: move_fn,
speed: spd_fn,
fn_run: function_runner
}
car.function_runner()
Car no longer has a method called function_runner, you've assigned it to the fn_run method, so you'd call car.fn_run(). Same thing with move_fn - renamed to move, and "acc_fn" isn't defined anywhere.
So it'd be:
var move_fn = function(){
var prev_position = this.position
this.position += + 1
console.log(this.type + " is moving from " + prev_position + " to " +
this.position + '.')
}
var spd_fn = function(){
var prev_speed = this.speed
console.log(this.position)
this.speed += this.position
console.log(this.type + ' is accelerating from ' + prev_speed + ' to ' +
this.speed + '.' )
}
var function_runner = function(){
this.move()
this.speed()
}
var car = {
type: 'Honda CRV',
position: 1,
speed: 30,
move: move_fn,
speed: spd_fn,
fn_run: function_runner
}
car.fn_run()
...although it is a strange way of structuring it.
I'm attempting to create a Choose Your Own Adventure type of game, and I'm currently trying to write a 'battle' script. What I've got so far is:
var name = "Anon";
var health = 100;
var youAttack = [name + " hits the " + opp + " with his sword", name + " uses magic!", name + " is too scared to fight!"];
var youBattle = function() {
var youBattle = youAttack[Math.floor(Math.random() * 3)];
return youBattle;
};
var opp = "Orc";
var oppHealth = 100;
var oppAttack = ["The " + opp + " hits you with his hammer!", "The " + opp + " does nothing!", "The " + opp + " back hands you!"];
var oppBattle = function() {
var oppBattle = oppAttack[Math.floor(Math.random() * 3)];
return oppBattle;
};
oppBattle();
youBattle();
I've done it like this so the opponent and player names can easily be changed.
What I'm struggling to figure out is how I can add / remove health from both the opponent and the player depending what attack is used. Obviously no health would be removed if the opp / player does nothing.
Is there a way I can do this without a bunch of messy if / else statements?
I was hoping for something easy like name + " hits the " + opp + " with his sword" + health = health - 10; but obviously that didn't work.
Thanks in advance!
http://jsbin.com/qerud/3/edit
Hope this isn't too much code:
var Attack = function(hero,opp,damageReceived,damageGiven,message){
this.message = message;
this.damageGiven = damageGiven;
this.damageReceived = damageReceived;
this.opp = opp;
this.hero = hero;
this.attack = function(opp){
this.hero.health -= damageReceived;
this.opp.health -= damageGiven;
return this.message;
};
};
var Character = function(name,health){
this.name = name;
this.health = health;
};
hero = new Character('Anon',100);
orc = new Character('Orc',150);
attack1 = new Attack(hero,orc,5,0,"The " + orc.name + " back hands you!");
attack2 = new Attack(hero,orc,0,0,hero.name + " is too scared to fight!");
attack3 = new Attack(hero,orc,15,0,"The " + orc.name + " hits you with his hammer!");
attack4 = new Attack(hero,orc,0,25,hero.name + " uses magic!");
attacks = [attack1,attack2,attack3,attack4];
while(hero.health > 0 && orc.health > 0){
console.log(attacks[Math.floor(Math.random() * 4)].attack());
console.log('Hero Health: '+ hero.health);
console.log('Orc Health: '+ orc.health);
}
if(hero.health > 0 ){
console.log(hero.name + ' won');
} else {
console.log('The ' + orc.name + ' won');
}
I can tell you first hand that trying to write this type of code uses a lot of if/else and more statements, regardless of what language you're using. You can use an array to hold the values of your attack patterns:
var attackName = ["Punch", "Sword", "Magic"]
var attackDamage = [3, 5, 4]
function youAttack(ATK, PHit) {
if(playerHit) {
playerDamage = ATK + PHit;
oppHealth = oppHealth - playerDamage;
return oppHeath;
} else {
alert("You missed!");
}
}
But, without seeing exactly what you're doing I cannot say how you should do your attacks and damages. I can only assume. You will need a system of evaluating attacks, misses, etc. that does use IF/ELSE Statements at least somewhere.
I am new to JS and have created this original problem from CodeAcademy which works. Now I wanted to put my flock of sheep into an object and access it using my sheepCounter function. I am new to accessing key/values from an object and am stuck on what I am doing wrong. Thanks in advance!
Original Code
var sheepCounter = function (numSheep, monthNumber, monthsToPrint) {
for (monthNumber = monthNumber; monthNumber <= monthsToPrint; monthNumber++) {
numSheep *= 4;
console.log("There will be " + numSheep + " sheep after " + monthNumber + " month(s)!");
}
return numSheep;
}
New Code:
var flock = {
sheep: 4,
month: 1,
totalMonths: 12
};
var sheepCounter = function (counter) {
for (counter[month] = counter[month]; counter[month] <= counter[totalMonths]; counter[month]++) {
numSheep *= 4;
console.log("There will be " + counter[sheep] + " sheep after " + counter[month] + " month(s)!");
}
return counter[sheep];
}
Found the error in your solution:
var sheepCounter = function (counter) {
for (counter['month'] = counter['month']; counter['month'] <= counter['totalMonths']; counter['month']++) {
counter['sheep'] *= 4;
console.log("There will be " + counter['sheep'] + " sheep after " + counter['month'] + " month(s)!");
}
return counter['sheep'];
}
You can access your Flock Object like so,
alert(flock.sheep); //4
If you have an array in an object, like
names: ['joe','tom','bob'];
You would access that like so,
alert(flock.names[0]); // joe
alert(flock.names[2]); // bob