Using object inheritance when both objects pass arguments - javascript

I have a Equipment parent class which takes in args and two children Weapon and Armor which also take args. I'm not sure if there is a special way to target prototypes or if my code actually isn't working but here is a shortened DEMO
I need to create the variables used for the arguments in each object based on the value of other variables as well as an algorithm that uses a random number. Each item is unique so I need to make the hp for equipment at the same time as the damage for weapons and I'm not sure how to do that.
function Equipment(hp) {
var self = this;
this.hp = hp;
}
//create subclass for weapons
function Weapon(baseDam) {
var self = this;
this.baseDam = baseDam;
}
function generateEquipment() {
hp = Math.round(Math.random() * 10);
baseDam = Math.round(Math.random() * 50);
Weapon.prototype = new Equipment(hp);
weapon = new Weapon(baseDam);
stringed = JSON.stringify(weapon);
alert(stringed);
}
generateEquipment();

First, the answer to your question :
Your code is not really wrong, and your weapon still has its hp, except that its contained in the objects prototype, so won't show when stringified.
There are ways to get around this, like I've shown here, but this according to me is not the correct way to do it.
Normally, prototypes should only store methods and not instance variables, because if you later decide to modify the prototype, the instance variable will get modified as well ,in case it is passed by reference.
A better pattern would be to use Object.assign - it is the easiest to understand and feels most natural. Further, if you expect Weapon to be a subclass of equipment, that logic should be encapsulated in Weapon itself.
Here is the proposed new way of declaring your Weapon Class :
function Weapon(baseDam) {
var self = this;
var hp = Math.round(Math.random() * 10);
Object.assign(self, Equipment.prototype, new Equipment(hp));
this.baseDam = baseDam;
}
Since hp is also generated randomly, that logic is now encapsulated in Weapon. This is also scalable, as this pattern will work for long inheritence chains as well.
Some people may recommend ES6 classes, which is also an approach that would work, but in my opinion it is syntactical sugar, which hides most of the inner workings of your code.
Here is a working demo with my approach.

The 'pattern' you're describing is called 'Composition' and can be very powerful. There're many different ways of combining/composing new classes or objects.
Reading your question and comments, it seems to me that you're mainly interested in defining many different types of equipment without too much (repeated) code.
Have you thought about passing an array of class names to your generateEquipment method and returning a new, custom constructor? Here's an example:
function Equipment(hp) {
this.hp = Math.round(hp);
}
Equipment.prototype.describe = function() {
return "This piece of equipment has " + this.hp + " hitpoints";
}
function Weapon(baseDam) {
this.baseDam = Math.round(baseDam);
}
Weapon.prototype.describe = function() {
return "The weapon does " + this.baseDam + " damage";
}
function generateCustomEquipment(types) {
var CustomEquipment = function() {
var self = this;
// Create the properties for all types
types.forEach(function(type) {
type.call(self, Math.random() * 100);
});
};
CustomEquipment.prototype.describe = function() {
var self = this;
// Combine the 'describe' methods of all composed types
return types
.map(function(type) {
return type.prototype.describe.call(self);
})
.join(". ");
}
return CustomEquipment;
}
var Sword = generateCustomEquipment([Equipment, Weapon]);
var Armor = generateCustomEquipment([Equipment]);
var Arrow = generateCustomEquipment([Weapon]);
var sword1 = new Sword();
document.writeln("A sword: " + sword1.describe() + "<br/>");
var armor1 = new Armor();
document.writeln("A piece of armor: " + armor1.describe() + "<br/>");
var arrow1 = new Arrow();
document.writeln("An arrow: " + arrow1.describe() + "<br/>");

Related

Repeating Value and Replacing Value with JS

Newbie in JS here. I'm having trouble replacing and repeating the value from the function. Here's the code:
function Phone(ring) {
this.ring = ring;
}
function updateRing(newRing) {
this.newRing = ring;
}
var samsung = new Phone('Chim');
samsung.ring(2); // Needs to compute to "Chim, Chim"
var htc = new Phone('Dada');
htc.ring(3); // Needs to compute to "Dada, Dada, Dada"
htc.updateRing('Riri');
htc.ring(1); // Needs to compute to "Riri"
For the repeat value for the first function, I tried using this.repeat but it didn't work inside the Phone function.
For the updateRing function, I couldn't get the code to replace the this.ring.
I stripped down all the useless code I had written. Thanks in advance for any help.
You can repeat strings with string.repeat()
let a = "ring"
console.log(a.repeat(2))
But to get the comma separator to work cleanly you can make a disposable array and join() is with a comma.
let ringString = Array(3).fill("ring").join(", ")
console.log(ringString)
For the others, you probably want to use classes, which are pretty easy, but don't run on IE without a ployfill. Or prototypes, which can be a little confusing at first. Here's an example using prototypes to define methods on your Phone object:
function Phone(ring) {
// changed to ring_tone too prevent clash with this.ring method
this.ring_tone = ring;
}
// you need to define these on the prototype to you can use `this`
Phone.prototype.updateRing = function(newRing) {
// don't need to define a this.newRing, just update the ring
this.ring_tone = newRing;
}
Phone.prototype.ring = function(n) {
return new Array(n).fill(this.ring_tone).join(', ')
}
var samsung = new Phone('Chim');
console.log(samsung.ring(2)); // Needs to compute to "Chim, Chim"
var htc = new Phone('Dada');
console.log(htc.ring(3)); // Needs to compute to "Dada, Dada, Dada"
htc.updateRing('Riri');
console.log(htc.ring(1)); // Needs to compute to "Riri"
1) You're calling samsung.ring as a function, even though it's just an instance variable of Phone.
2) The reason why this.repeat didn't work is because repeat isn't a method of "this," which refers to Phone.
Try this instead:
var samsung = new Phone('Chim');
samsung.ring.repeat(2);
var htc = new Phone('Dada');
htc.ring.repeat(3);
Maybe try this:
class Phone {
constructor(sound) {
this.sound = sound;
}
ring(number) {
var i;
for (i = 0; i < number; i++) {
console.log(this.sound + ", ");
}
}
updateRing(newSound) {
this.sound = newSound;
}
}
var samsung = new Phone('Chim');
samsung.ring(2);
samsung.updateRing('Riri');
samsung.ring(1);
Codepen - https://codepen.io/anon/pen/MGRJOB?editors=0010

Adding methods to prototype objects in JavaScript

I'm making my way through Murach’s JavaScript and jQuery (3rd Edition) and I've encountered a compiler error with code from the book. I've triple checked my syntax against the book's syntax and I think I can rule it out. I also looked at the errata page and I don't find a reference to the page I'm on.
I also looked at this question, but I didn't find anything applicable to my issue.
Here is my object constructor:
var Invoice = function(subtotal, taxRate) {
this.subtotal = subtotal;
this.taxRate = taxRate;
};
I run into trouble when attempting to add methods to the prototype object:
// The getTaxAmount method is added to the Invoice prototype
Invoice.prototype.getTaxAmount: function() {
// Compiler whines right here ^ and ^
return (subtotal * this.taxRate);
};
// The getInvoiceTotal method is added to the Invoice prototype
Invoice.prototype.getInvoiceTotal: function() {
// Compiler whines right here ^ and ^
return subtotal + this.getTaxAmount(this.subtotal);
};
I'm using Visual Studio Code with Debugger for Chrome. The prompt in VS Code says it wants a ; at the first spot it complains and [js] identifier expected at the second spot it complains.
Thank you for reading. I welcome your suggestions.
The syntax is either
Invoice.prototype.getInvoiceTotal = function() {}
This is because prototype itself is an object.
Yes, that's a syntax error. You rather use an assignment operator, =, for such work:
// The getTaxAmount method is added to the Invoice prototype
Invoice.prototype.getTaxAmount = function() {
return (subtotal * this.taxRate);
};
// The getInvoiceTotal method is added to the Invoice prototype
Invoice.prototype.getInvoiceTotal = function() {
return subtotal + this.getTaxAmount(this.subtotal);
};
In addition to that, you could use Object.assign to assign properties to an object, like this:
Object.assign(Invoice.prototype, {
getTaxAmount: function() {
return (subtotal * this.taxRate);
},
getInvoiceTotal: function() {
return subtotal + this.getTaxAmount(this.subtotal);
}
});
Notice that you don't use a semicolon at the end of the function when using the latter.
According to w3Schools, the correct way to add a function to a prototype would be as follows:
Invoice.prototype.getInvoiceTotal = function(){ **your fx here** };
From the look of things, you are using a : instead of a =, this may be what is causing you grief.
Try using an equal sign. Colon is for variable values for JSON.
Invoice.prototype.getInvoiceTotal = function() {
// Compiler whines right here ^ and ^
return subtotal + this.getTaxAmount(this.subtotal);
};
All JavaScript objects inherit properties and methods from a prototype.
The JavaScript prototype property also allows you to add new methods objects constructors:
ie : Date objects inherit from Date.prototype. Array objects inherit from Array.prototype. Person objects inherit from Person.prototype.
<script>
var Invoice = function(subtotal, taxRate) {
this.subtotal = subtotal;
this.taxRate = taxRate;
};
Invoice.prototype.getTaxAmount = function() {
return (subtotal * this.taxRate);
};
var myTax= new Invoice(10,5);
document.getElementById("demo").innerHTML =
"My tax amount is " + myTax.getTaxAmount ();
</script>

HTML5 game objects and sharing methods

I'm having some issues understanding the code below for HTML5 game. This what i think is happening and was wondering if my understanding is correct?
1) When the Entity function is called, the object SELF is created along with its method (test collision)
2) When the Enemy object is created, it calls the function 'actor' and INHERITS the functions from the SELF object (because self refers to itself) but it also INHERITS the perform.attack method
I'm not sure why we return the object, but in short, by creating the SELF object we can share methods, behaviors and properties allowing us to create DRY code?
I hope my understanding is correct?
Entity = function(type,id,x,y,spdX,spdY,width,height,color){
// a function to call
var self = {
type:type,
x:x,
spdX:spdX,
y:y,
spdY:spdY,
width:width,
height:height,
color:color,
};
self.testCollision = function(entity2){
var rect1 = {
x:self.x-self.width/2,
y:self.y-self.height/2,
width:self.width,
height:self.height,
}
var rect2 = {
x:entity2.x-entity2.width/2,
y:entity2.y-entity2.height/2,
width:entity2.width,
height:entity2.height,
}
return testCollisionRectRect(rect1,rect2);
}
return self;
}
//---------actor can be an enemy or player in the game-----//
Actor = function(type,id,x,y,spdX,spdY,width,height,color){
var self = Entity(type,id,x,y,spdX,spdY,width,height,color);
self.attackCounter = 0;
self.aimAngle = 0;
self.atkSpd = 1;
self.performAttack = function(){
if(self.attackCounter > 25){ //every 1 sec
self.attackCounter = 0;
generateBullet(self);
}
}
return self;
}
// ------------------Create the enemy function----------- //
Enemy = function(id,x,y,spdX,spdY,width,height){
var self = Actor('enemy',id,x,y,spdX,spdY,width,height,'red');
enemyList[id] = self;
}
randomlyGenerateEnemy = function(){
//Math.random() returns a number between 0 and 1
var x = Math.random()*WIDTH;
var y = Math.random()*HEIGHT;
var height = 10 + Math.random()*30; //between 10 and 40
var width = 10 + Math.random()*30;
var id = Math.random();
var spdX = 5 + Math.random() * 5;
var spdY = 5 + Math.random() * 5;
Enemy(id,x,y,spdX,spdY,width,height);
}
Thank for the help.
P
JavaScript doesn't have native inheritance. JavaScript doesn't even classes to inherit from, yet -- but JS6 has classes.
Entity is a factory that creates & returns anonymous self objects with properties & a testCollision method.
Actor requests a new object from Entity. Actor adds properties & a performAttack method to the requested object and returns that extended object.
Enemy requests a new object from Actor. Enemy adds that object to an array.
If we examine only this code
If this is the only time Entity & Actor are used then the code is un-necessarily broken into parts. The entire final object (all properties & all methods included) could most efficiently be built in randomlyGenerateEnemy.
If there is more code that uses Entity & Actor
Presumably(!) ...
Entity creates the properties and methods that are common to all game pieces (pieces == characters, structures, etc). To borrow a math phrase, Entity creates an object with the "most common denominators".
Actor enhances the basic Entity object with properties and methods that are inherent to Actor game characters.
Enemy simply adds a new Actor object to the enemyList.
Presumably there might also be a Structure function which (like Actor) enhances the basic Entity object with properties and methods that are inherent to Structure game pieces.
Presumably there might also be a Buildings function which (like Enemy) simply adds a new Structure object to a buildingsList.
Since the Entity code is being reused by both Actor & Structure in the presumed code, the presumed code would make use of the DRY (Don't Repeat Yourself) coding pattern.

How to set a dynamically generated pseudoclass name in JavaScript to work with the instanceof operator?

I'd like to set the name of a JavaScript pseudoclass stored in an array with a specific name, for example, the non-array version works flawlessly:
var Working = new Array();
Working = new Function('arg', 'this.Arg = arg;');
Working.prototype.constructor = Working;
var instw = new Working('test');
document.write(instw.Arg);
document.write('<BR />');
document.write((instw instanceof Working).toString());
Output:
test
true
However this format does not function:
// desired name of pseudoclass
var oname = 'Obj';
var objs = new Array();
objs.push(new Function('arg', 'this.Arg = arg;'));
// set objs[0] name - DOESN'T WORK
objs[0].prototype.constructor = oname;
// create new instance of objs[0] - works
var inst = new objs[0]('test');
document.write(inst.Arg);
document.write('<BR />Redundant: ');
// check inst name - this one doesn't need to work
try { document.write((inst instanceof objs[0]).toString()); } catch (ex) { document.write('false'); }
document.write('<BR />Required: ');
// check inst name - this is the desired use of instanceof
try { document.write((inst instanceof Obj).toString()); } catch (ex) { document.write('false'); }
Output:
test
Redundant: true
Required: false
Link to JSFiddle.
You've got a couple of things going on here that are a little bit off-kilter in terms of JS fluency (that's okay, my C# is pretty hackneyed as soon as I leave the base language features of 4.0).
First, might I suggest avoiding document.write at all costs?
There are technical reasons for it, and browsers try hard to circumvent them these days, but it's still about as bad an idea as to put alert() everywhere (including iterations).
And we all know how annoying Windows system-message pop-ups can be.
If you're in Chrome, hit CTRL+Shift+J and you'll get a handy console, which you can console.log() results into (even objects/arrays/functions), which will return traversable nodes for data-set/DOM objects and strings for other types (like functions).
One of the best features of JS these days is the fact that your IDE is sitting in your browser.
Writing from scratch and saving .js files isn't particularly simple from the console, but testing/debugging couldn't be any easier.
Now, onto the real issues.
Look at what you're doing with example #1.
The rewriting of .prototype.constructor should be wholly unnecessary, unless there are some edge-case browsers/engines out there.
Inside of any function used as a constructor (ie: called with new), the function is basically creating a new object {}, assigning it to this, setting this.__proto__ = arguments.callee.prototype, and setting this.__proto__.constructor = arguments.callee, where arguments.callee === function.
var Working = function () {};
var working = new Working();
console.log(working instanceof Working); // [log:] true
Working isn't a string: you've make it a function.
Actually, in JS, it's also a property of window (in the browser, that is).
window.Working === Working; // true
window["Working"] === Working; // true
That last one is really the key to solving the dilemma in example #2.
Just before looking at #2, though, a caveat:
If you're doing heavy pseud-subclassing,
var Shape = function () {
this.get_area = function () { };
},
Square = function (w) {
this.w = w;
Shape.call(this);
};
If you want your instanceof to work with both Square and Shape, then you have to start playing with prototypes and/or constructors, depending on what, exactly, you'd like to inherit and how.
var Shape = function () {};
Shape.prototype.getArea = function () { return this.length * this.width; };
var Square = function (l) { this.length = l; this.width = l; };
Square.prototype = new Shape();
var Circle = function (r) { this.radius = r; };
Circle.prototype = new Shape();
Circle.prototype.getArea = function () { return 2 * Math.PI * this.radius; };
var circle = new Circle(4),
square = new Square(4);
circle instanceof Shape; // true
square instanceof Shape; // true
This is simply because we're setting the prototype object (reused by every single instance) to a brand-new instance of the parent-class. We could even share that single-instance among all child-classes.
var shape = new Shape();
Circle.prototype = shape;
Square.prototype = shape;
...just don't override .getArea, because prototypical-inheritance is like inheriting public-static methods.
shape, of course, has shape.__proto__.constructor === Shape, much as square.__proto__.constructor === Square. Doing an instanceof just recurses up through the __proto__ links, checking to see if the functions match the one given.
And if you're building functions in the fashion listed above (Circle.prototype = new Shape(); Circle.prototype.getArea = function () { /* overriding Shape().getArea() */};, then circle instanceof Circle && circle instanceof Shape will take care of itself.
Mix-in inheritance, or pseudo-constructors (which return objects which aren't this, etc) require constructor mangling, to get those checks to work.
...anyway... On to #2:
Knowing all of the above, this should be pretty quick to fix.
You're creating a string for the desired name of a function, rather than creating a function, itself, and there is no Obj variable defined, so you're getting a "Reference Error": instead, make your "desired-name" a property of an object.
var classes = {},
class_name = "Circle",
constructors = [];
classes[class_name] = function (r) { this.radius = r; };
constructors.push(classes.Circle);
var circle = new constructors[0](8);
circle instanceof classes.Circle;
Now everything is nicely defined, you're not overwriting anything you don't need to overwrite, you can still subclass and override members of the .prototype, and you can still do instanceof in a procedural way (assigning data.name as a property of an object, and setting its value to new Function(data.args, data.constructor), and using that object-property for lookups).
Hope any/all of this helps.

Need help understanding object oriented approach to Javascript

Can someone help me understand the object oriented approach to javascript? I am used to writing js code as follows:
function o_deal(id) {
var hand = gcard1 + ", " + gcard2;
var res = gcard1_val + gcard2_val;
document.getElementById(id).innerHTML = hand;
if (res == 21) {
alert("Blackjack!");
}
if (bucket == 0) {
bucket = " ";
}
var card3_val = Math.floor(Math.random() * deck.length);
var nhand = deck[card3_val];
bucket = bucket + " " + nhand + ", ";
bucket_val = bucket_val + gcard1_val + gcard2_val + card3_val;
if (bucket_val >= 22) {
var r = confirm("Bust! By " + nhand);
if (r == true) {
refresh();
}
else {
refresh();
}
}
document.getElementById(id).innerHTML = bucket;
}
But I've seen a number of posters on stack overflow that write code like this:
var Hand = function(bjcallback) {
this.cards = [];
this.onblackjack = bjcallback;
this.deck = [1,2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"];
this.values = {
"Jack": 10,
"Queen": 10,
"King": 10,
"Ace": 11
};
this.sum = function() {
var i, x, res = 0;
for (i in this.cards) {
x = this.cards[i];
if (typeof(x) != 'number') { x = this.values[x] };
res += x;
};
return res
};
this.pick = function() {
var pos = Math.floor(Math.random() * this.deck.length);
var card = this.deck[pos];
console.log(card);
return card
};
this.deal = function(n) {
n = n || 2;
Can someone please break the second method down so I can understand the difference? Any help would be appreciated.
Object orientation in javascript is not two hard. You just bundle functionality and data together.
So we have some functionality.
I'll just look at this snippet
function o_deal(id) {
var hand = gcard1 + ", " + gcard2,
res = gcard1_val + gcard2_val;
document.getElementById(id).innerHTML = hand;
if (res == 21) {
alert("Blackjack!");
}
}
Let's refactor this. We would need a few functions
isBlackjack. for checking whether we've won.
toString for rendering the hand
Now we need to define hand.
var Hand = {
"isBlackjack": function() {
return this.cards[0].value + this.cards[1].value === 21;
},
"toString": function() {
return this.cards[0].toString() + " " + this.cards[1].toString();
}
}
Now we can refactor o_deal to
function o_deal(id, hand) {
document.getElementById(id).innerHTML = hand.toString();
if (hand.isBlackjack()) {
alert("Blackjack!");
}
}
Of course we still need the concepts of cards and we need to be able to make a hand.
Making a hand is easy. var hand = Object.create(Hand)
We also need a Card object which needs a toString method
var CardList = [null, "1","2","3","4","5","6","7","8","9","X","A"];
var Card = {
"toString": function() {
return CardList[this.value];
}
}
Now we just need a way to create a hand
var createHand = function() {
var hand = Object.create(Hand);
var card1 = Object.create(Card);
var card2 = Object.create(Card);
card1.value = Math.floor(Math.random() * 11);
card2.value = Math.floor(Math.random() * 11);
hand.cards = [card1, card2];
return hand;
}
Now hopefully you can see how encapsulation and binding data and functionality together is useful.
Douglas Crockford is your man. He has a series of articles that really delve into the finer points of JavaScript. I recommend reading all of the articles:
http://javascript.crockford.com/
This one explains JavaScript's OO syntax:
http://javascript.crockford.com/private.html
object oriented comes into play when the whole thing is in Class.
Object oriented code is for organization and reusability. So in your second example, you have a class Hand, that you can create new instances of. So every time you want to create a new hand of cards for a player, you could do:
var playerHand = new Hand(options);
and pass in parameters to the class, which would be used to differentiate one hand from the other.
this.deck, this.cards, etc. are properties of the object, and this.sum, this.pick, etc are methods. These methods (or simply functions) can act upon the public and private properties of the object.
This particular example of OO code wouldn't be a real world example (or at least I wouldn't organize it that way). The "deal" method would be part of the CardDealer class.
So you would have the following Classes/Objects (amongst others), from which you can create new instances:
Dealer, Player, Hand, Card, Game
(Mind you, this is just one approach, as you mentioned, there are many ways to go about this)
The Game object could have a "type" property, in which case it would be blackjack. The Game object could then be responsible for loading the appropriate rules for blackjack. One instance of Dealer would be needed, and X amount of Player objects as well, and each would have a Hand object associated with it.
This way, each object is responsible for its own properties and actions (methods). It keeps everything organized and encapsulated.
As I'm writing this, #Raynos just posted examples of rewriting your procedural code as OO, so hopefully this might help you with the whys instead of the hows.

Categories