I'm relatively new to Javascript. I was wondering if it supports components and objects like Python does. If it does, what would the syntax look like?
For instance, I know an object look like this:
function Foo(a, b) {
this.a = a;
this.b = b;
}
Now, is there a way to declare some components, pick one of those, and add it to the object? For instance, let's say I have a object Item. Could I declare some different components, such as Weapon, Magical, Legendary, etc. and them add them to the object? Using this approach I could end up with a Magical Weapon, or a Legendary Item, or even a Legendary Magical Weapon.
I thought about using parenting for this but for what I want to do, it seems like that would be rather limited. For instance, my heirarchy would look like Item/Weapon or Item/Legendary, so I couldn't have a Legendary Weapon.
So, are components possible in Javascript?
What you describe as a 'component' is more commonly called a class. What you describe as 'parenting' is more commonly called inheritance. You are spot on about the class hierarchy :)
Ok, so your base class in an Item. This item will have the basic attributes which all items in your game world must have. All objects in your game world will inherit from Item.
A Weapon is an Item. A MagicalItem is an Item. A LegendaryItem is an item. These three classes are all subclasses of Item.
Things get a little bit more tricky when you want a LegendaryMagicalWeaponItem. This is the essence of your question: Is multiple inheritance possible in JavaScript?
To paraphrase the Boondock Saints, you do not want multiple inheritance unless you are absolutely, positively sure that you need it. Why? It quickly leads to complications. For example, what if two superclasses have a method or an attribute with the same name? What if they inherit from two different base classes, and one of those classes causes a name collision? You can see where this is going.
Fortunately, JavaScript, like Python, is a very flexible language. You are not forced to use multiple inheritance or even interfaces to generalise behaviour across heterogeneous objects.
Let's say MagicalItem has a mana property and LegendaryItem has a legacy() method. Let's say a weapon object has a damage. Let's say Item has important physical attributes and a bunch of physics methods; it is clearly the 'dominant' superclass. There is nothing stopping you from doing this:
// Base classes
function Item() {
// some default values...
}
Item.prototype.physics = function (t) {/* physics stuff */}
function Magical(mana) {
this.mana = mana;
}
function Weapon(damage) {
this.damage = damage;
}
function Legendary(legacy) {
this.legacy = function () {return legacy;};
}
// Actual world item class
function MyLegendaryMagicalSword(x,y) {
this.x = x;
this.y = y;
Weapon.call(this, MyLegendaryMagicalSword.DAMAGE);
Legendary.call(this, MyLegendaryMagicalSword.LORE);
Magical.call(this, MyLegendaryMagicalSword.START_MANA);
}
// actual prototypal inheritance
MyLegendaryMagicalSword.prototype = new Item();
// class attributes
MyLegendaryMagicalSword.DAMAGE = 1000;
MyLegendaryMagicalSword.START_MANA = 10;
MyLegendaryMagicalSword.LORE = "An old sword.";
// Sword instance
var sword = new MyLegendaryMagicalSword(0, 0);
sword.physics(0);
sword.mana;
sword.legacy();
// etc
// probe object for supported interface
if (sword.hasOwnProperty("damage")) {
// it's a weapon...
}
This is a down and dirty way to do what you describe.
> sword
{ x: 0,
y: 0,
damage: 1000,
legacy: [Function],
mana: 10 }
I have no idea what you mean by components. The term is too generalized. In Delphi, a component is a non-visible code module which introduces some special functionality to the application. A "timer" is one such example of a component (in Delphi).
Guessing from your description, you seem to want to add properties dynamically? Or is it about overloading?
In the latter case, you can't do this by design, as in, it lifts the limitations you mentioned.
Example (mixing):
function mixItems(weapon,legend){
return {
"damage":legend.damage+weapon.damage,
"name":legend.name+"' "+weapon.name
};
}
var weapon={ "damage":45, "name":"sword"};
var legend={ "name":"Goliath", "damage":34 };
var LegendaryWeapon = mixItems(weapon,legend);
console.log( LegendaryWeapon );
// output:- name: "Goliath's sword", damage: 79
Example (extending):
function clone(old){ // non-deep cloning function
var res={};
for(i in old)
res[i]=old[i];
return res;
}
var sword = {
"damage":50
"hit": function(){ // returns the percentage hit chance
return Math.round(Math.random()*100);
}
};
var bigsword=clone(sword);
bigsword.damage=60;
bigsword.hit=function(){ // returns the percentage hit chance
return Math.round(Math.random()*80)+20;
};
an object in javascript looks like this:
var Foo = {
a: null,
b: null,
init: function(a,b){
this.a = a;
this.b = b;
}
}
//call the init:
Foo.init(12,34);
almost the same as you have in the question.
And this object is extendable
you code example is a Function object which is intended to be used as a constructor function i.e. call it with the new keyword and it returns an instance of an object that has an a property and a b property (amongst other inherited properties).
Function objects inherit from Object like all other objects in JavaScript.
Usually, objects are created using object literal syntax, i.e. var x = { a: 'a', b: 'b' }; although they can also be created by using the new keyword with Object.
It looks like your question is referring to inheritance with JavaScript. Well, there are many ways to perform inheritance. One example is
function A() { }
function B() { }
B.prototype = new A;
Here both A and B are constructor functions. Functions have a prototype property which is an object and can contain members that can be shared by all object instances constructed by the function. We assign an instance of an object returned by the constructor function A to B's prototype, giving B all members available on an instance of A. This is just one way to perform inheritance in JavaScript.
The Mozilla Developer Center article on the Object Model is worth a read.
Related
Assume we have some classes A and B:
Class A {
constructor(a) {
this.a = a;
};
showInfo() {
console.log(this.a)
};
};
Class B {
constructor(b) {
this.b = b;
};
printText() {
console.log('its B!');
};
};
Then we create an instance of B like this:
const objB = new B(
new A(3)
);
So now we have objB with its own method inside - printText, and we surely can call it.
But what if i want somehow when calling not existing method in objB to make it pass through to encapsulated A class in there and look for invoking this method on him, like this: objB.showInfo() - to give me 3 here ?
Same story, but at this time i want when calling not existing method on A to make it pass through to B outside (like that printText)?
P.S. Don't wanna use super() and inheritance, just composition and wrapping objects, hope you've got the point.
Just a little warning at the start: this might make your program harder to debug, and it also might be a little complicated for something like this. As others have suggested, you should probably investigate other options which may be simpler and also less in the way of everything else your code does.
Here's the code which provides the functionality:
function makeGetProxy(t){
return new Proxy(t, {
get(obj,prop){
if(prop in t){
return t[prop];
}else{
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var val = t[keys[i]];
if(prop in val){
return val[prop];
// what about a recursive function?
}
}
return undefined;
}
}
});
}
And one itty bitty change to your constructor in B:
class B {
constructor(b) {
this.b = b;
return makeGetProxy(this);
};
printText() {
console.log('its B!');
};
};
If you want, you can also do the same to A.
Let's slow down. What just happened? I'll explain.
Since the properties we might request don't already exist, we're going to have to use a getter (see resources) to properly send back the value required. But, since we don't know the property names, we need a Proxy (see resources) to have a "catch-all" kind of get method.
The proxy will check if the property requested prop already exists, and if so, returns it. If it doesn't exist, it checks all of your properties' properties (all of the sub-properties).
The first result it gets, it returns it. This might cause unexpected bugs in your program. If it doesn't find it, it simply returns undefined.
Then, the proxy is generalized into a function for reuse in multiple classes (as you requested).
So, this can get the properties of a class and the properties of a class' properties, but if you need to go further (with your C class that doesn't exist yet), you can use a recursive function. I currently don't have the implementation for that recursive function, but in my head it would comprise mostly of a modified version of the else block in the makeGetProxy function.
Again, be careful with this code. It might get in the way of other things and cause unnecessary difficulty in debugging.
Resources:
Getters (MDN)
Proxy (MDN)
I borrowed some code from this answer and got the Proxy idea from this answer.
This may be a non-problem, but I have a feeling learning about proper practices will help me learn proper javascript techniques! I'm just starting with using objects and attaching functions to them. Here is the current setup I am using for a little combat simulator:
var standardAttack = function(attacker,target){
if(!target.alive) return false;
var damage = r(attacker.damage)+1-target.def;
if(damage>0) {
target.hp -= damage;
sendMessage(attacker.name+" hits "+target.name+" for "+damage.toString());
if(target.hp<1){
sendMessage(target.name+[" is torn asunder!"," has it's head ripped off!"," is trampled into the dirt!"," is sliced in half!"," is smashed to pieces!"," falls to the ground, gurgling!"," flails and dies on the ground!"].sample()+" by "+attacker.name);
target.alive = false;
}
} else {
sendMessage(attacker.name+" hits "+target.name+" but no damage is dealt");
}
}
While the Creature object looks like this:
class Creature {
constructor() {
this.name = getName();
this.alive = true;
this.hp = 6;
this.def = 0;
this.damage = 6;
this.attack = standardAttack;
}
}
There are various different types of attacks in a similar format to standardAttack, and when needed, creature.attack is changed.
From this, attacks are started with:
creature1.attack(creature1,creature2);
or something along those lines. Looking at this, I feel like there is a more efficient way to access creature1.name and creature1.damage than passing itself into it's own function, a needless duplication. In addition, I don't think I am wrong in saying that it just looks bad! I feel that a more suitable format would be:
creature1.attack(creature2);
But currently, the standardAttack function is unable to find the damage or name values of the creature1 object. My question is this - is there any way to access the details of creature1 without passing the whole object into it's own function?
Please let me know if there are any changes I need to make to the question as well.
You have a few options. For a SO post on "this": How does the "this" keyword work?
Option 1, minimal code change:
You can bind your attack function to the current class so that your attack function has access to the "this" context. e.g.:
class Creature {
constructor() {
this.attack = standardAttack.bind(this)
}
}
In your standardAttack definition:
function standardAttack(target) {
console.log(this.attack)
}
Alternatively, using the same bind approach, whenever you call creature.attack you can make sure it's called with the correct context, e.g.: creature.attack.call(creature, target).
Option 2, better OOP pattern:
Define a method of the class "attack" so that "attack" semantically belongs to the Creature rather than some generic function. In JavaScript this is nothing more than semantics since you'll still need to make sure the method is called with the correct context -- or bind the method to the right context via the approach mentioned above.
class Creature {
attack(target) {
console.log(this.attack)
}
}
If you're using babel with the right rule enabled (I think class fields? / property initializers) you can do this shorthand which will automatically bind the method to the class instance. Word of caution, it doesn't add it to the prototype chain.
class Creature {
attack = target => {
console.log(target)
}
}
If "attack" is shared by multiple entities, you can define the method in some base class and inherit it:
class AggressiveEntity {
attack() {}
}
class Creature extends AggressiveEntity {}
I am reading about prototipcal inheritance. There, and from elsewhere, I am learning this style of avoiding classical inheritance which I am still digesting.
One aspect that still puzzles me, though, is the this pointer, which is said to cause confusion for many like myself who come from classic OO languages. (If I were to avoid classic inheritance, shouldn't I be avoiding this as well?
)
After some reading, I realize that the this pointer is defined not at the time of object/function definition (as in C++) but rather at the site of function call. The this pointer seems (to me) like a dangling pointer whose target depends on where/how you use it.
Using an example in the linked blog article about extending objects, can someone help explain the following:
Can we avoid using this or replacing it with explicit object reference?
A related question is, is the this pointer necessary if I only use prototypical inheritance?
Example from the blog:
It would be nice to combine these two operations into one, ... and
extend it with new properties. This operation, called extend, can be
implemented as a function:
1 Object.prototype.extend = function (extension) {
2 var hasOwnProperty = Object.hasOwnProperty;
3 var object = Object.create(this);
4
5 for (var property in extension)
6 if (hasOwnProperty.call(extension, property) ||
7 typeof object[property] === "undefined")
8 object[property] = extension[property];
9
10 return object;
11 };
Using the above extend function we can rewrite the code for square as
follows:
1 var square = rectangle.extend({
2 create: function (side) {
3 return rectangle.create.call(this, side, side);
4 }
5 });
6
7 var sq = square.create(5);
8
9 alert(sq.area());
Note, this is used in line 3 of both code segments.
If you want to avoid this completely, then you should step away from creating methods that act on the object they are applied on, meaning that you should not have method calls like obj.method(), where method needs to use the state of obj in some way.
So the effect of the following should be the same as obj.method():
var method = obj.method;
method();
In places where the above would fail, you'll need to refactor the code, so that you can in principle use it like this without problems:
var method = obj1.method;
method(obj2); // apply method on obj2
So, in general you'll need to create utility functions that take one more argument: the object to apply the logic on.
In your case this would mean that you don't define extend on Object.prototype (which is considered bad practice anyway), but on Object itself, and give it the extra source object parameter. This is also how many native methods are defined, like Object.assign, Object.keys, et al. Also the definition of rectangle will need some changes to make it work without ever using this:
Object.extend = function (source, extension) {
var hasOwnProperty = Object.hasOwnProperty;
var object = Object.create(source);
for (var property in extension)
if (hasOwnProperty.call(extension, property) ||
typeof object[property] === "undefined")
object[property] = extension[property];
return object;
};
var rectangle = {
create: function (width, height) {
var self = {
width: width,
height: height,
area: function () {
return self.width * self.height;
}
};
return self;
}
};
var square = Object.extend(rectangle, {
create: function (side) {
return rectangle.create(side, side);
}
});
var sq = square.create(5);
console.log(sq.area());
As you have realised, there are lots of ways to work with objects and implement some form of inheritance in JavaScript, and each has its pros and cons.
I've read pages and pages about JavaScript prototypal inheritance, but I haven't found anything that addresses using constructors that involve validation. I've managed to get this constructor to work but I know it's not ideal, i.e. it's not taking advantage of prototypal inheritance:
function Card(value) {
if (!isNumber(value)) {
value = Math.floor(Math.random() * 14) + 2;
}
this.value = value;
}
var card1 = new Card();
var card2 = new Card();
var card3 = new Card();
This results in three Card objects with random values. However, the way I understand it is that each time I create a new Card object this way, it is copying the constructor code. I should instead use prototypal inheritance, but this doesn't work:
function Card(value) {
this.value = value;
}
Object.defineProperty( Card, "value", {
set: function (value) {
if (!isNumber(value)) {
value = Math.floor(Math.random() * 14) + 2;
}
this.value = value;
}
});
This doesn't work either:
Card.prototype.setValue = function (value) {
if (!isNumber(value)) {
value = Math.floor(Math.random() * 14) + 2;
}
this.value = value;
};
For one thing, I can no longer call new Card(). Instead, I have to call var card1 = new Card(); card1.setValue(); This seems very inefficient and ugly to me. But the real problem is it sets the value property of each Card object to the same value. Help!
Edit
Per Bergi's suggestion, I've modified the code as follows:
function Card(value) {
this.setValue(value);
}
Card.prototype.setValue = function (value) {
if (!isNumber(value)) {
value = Math.floor(Math.random() * 14) + 2;
}
this.value = value;
};
var card1 = new Card();
var card2 = new Card();
var card3 = new Card();
This results in three Card objects with random values, which is great, and I can call the setValue method later on. It doesn't seem to transfer when I try to extend the class though:
function SpecialCard(suit, value) {
Card.call(this, value);
this.suit = suit;
}
var specialCard1 = new SpecialCard("Club");
var specialCard2 = new SpecialCard("Diamond");
var specialCard3 = new SpecialCard("Spade");
I get the error this.setValue is not a function now.
Edit 2
This seems to work:
function SpecialCard(suit, value) {
Card.call(this, value);
this.suit = suit;
}
SpecialCard.prototype = Object.create(Card.prototype);
SpecialCard.prototype.constructor = SpecialCard;
Is this a good way to do it?
Final Edit!
Thanks to Bergi and Norguard, I finally landed on this implementation:
function Card(value) {
this.setValue = function (val) {
if (!isNumber(val)) {
val = Math.floor(Math.random() * 14) + 2;
}
this.value = val;
};
this.setValue(value);
}
function SpecialCard(suit, value) {
Card.call(this, value);
this.suit = suit;
}
Bergi helped me identify why I wasn't able to inherit the prototype chain, and Norguard explained why it's better not to muck with the prototype chain at all. I like this approach because the code is cleaner and easier to understand.
the way I understand it is that each time I create a new Card object this way, it is copying the constructor code
No, it is executing it. No problems, and your constructor works perfect - this is how it should look like.
Problems will only arise when you create values. Each invocation of a function creates its own set of values, e.g. private variables (you don't have any). They usually get garbage collected, unless you create another special value, a privileged method, which is an exposed function that holds a reference to the scope it lives in. And yes, every object has its own "copy" of such functions, which is why you should push everything that does not access private variables to the prototype.
Object.defineProperty( Card, "value", ...
Wait, no. Here you define a property on the constructor, the function Card. This is not what you want. You could call this code on instances, yes, but note that when evaluating this.value = value; it would recursively call itself.
Card.prototype.setValue = function(){ ... }
This looks good. You could need this method on Card objects when you are going to use the validation code later on, for example when changing the value of a Card instance (I don't think so, but I don't know?).
but then I can no longer call new Card()
Oh, surely you can. The method is inherited by all Card instances, and that includes the one on which the constructor is applied (this). You can easily call it from there, so declare your constructor like this:
function Card(val) {
this.setValue(val);
}
Card.prototype...
It doesn't seem to transfer when I try to extend the class though.
Yes, it does not. Calling the constructor function does not set up the prototype chain. With the new keyword the object with its inheritance is instantiated, then the constructor is applied. With your code, SpecialCards inherit from the SpecialCard.prototype object (which itself inherits from the default Object prototype). Now, we could either just set it to the same object as normal cards, or let it inherit from that one.
SpecialCard.prototype = Card.prototype;
So now every instance inherits from the same object. That means, SpecialCards will have no special methods (from the prototype) that normal Cards don't have... Also, the instanceof operator won't work correctly any more.
So, there is a better solution. Let the SpecialCards prototype object inherit from Card.prototype! This can be done by using Object.create (not supported by all browsers, you might need a workaround), which is designed to do exactly this job:
SpecialCard.prototype = Object.create(Card.prototype, {
constructor: {value:SpecialCard}
});
SpecialCard.prototype.specialMethod = ... // now possible
In terms of the constructor, each card IS getting its own, unique copy of any methods defined inside of the constructor:
this.doStuffToMyPrivateVars = function () { };
or
var doStuffAsAPrivateFunction = function () {};
The reason they get their own unique copies is because only unique copies of functions, instantiated at the same time as the object itself, are going to have access to the enclosed values.
By putting them in the prototype chain, you:
Limit them to one copy (unless manually-overridden per-instance, after creation)
Remove the method's ability to access ANY private variables
Make it really easy to frustrate friends and family by changing prototype methods/properties on EVERY instance, mid-program.
The reality of the matter is that unless you're planning on making a game that runs on old Blackberries or an ancient iPod Touch, you don't have to worry too much about the extra overhead of the enclosed functions.
Also, in day-to-day JS programming, the extra security from properly-encapsulated objects, plus the extra benefit of the module/revealing-module patterns and sandboxing with closures VASTLY OUTWEIGHS the cost of having redundant copies of methods attached to functions.
Also, if you're really, truly that concerned, you might do to look at Entity/System patterns, where entities are pretty much just data-objects (with their own unique get/set methods, if privacy is needed)... ...and each of those entities of a particular kind is registered to a system which is custom made for that entity/component-type.
IE: You'd have a Card-Entity to define each card in a deck.
Each card has a CardValueComponent, a CardWorldPositionComponent, a CardRenderableComponent, a CardClickableComponent, et cetera.
CardWorldPositionComponent = { x : 238, y : 600 };
Each of those components is then registered to a system:
CardWorldPositionSystem.register(this.c_worldPos);
Each system holds ALL of the methods which would normally be run on the values stored in the component.
The systems (and not the components) will chat back and forth, as needed to send data back and forth, between components shared by the same entity (ie: the Ace of Spade's position/value/image might be queried from different systems so that everybody's kept up to date).
Then instead of updating each object -- traditionally it would be something like:
Game.Update = function (timestamp) { forEach(cards, function (card) { card.update(timestamp); }); };
Game.Draw = function (timestamp, renderer) { forEach(cards, function (card) { card.draw(renderer); }); };
Now it's more like:
CardValuesUpdate();
CardImagesUpdate();
CardPositionsUpdate();
RenderCardsToScreen();
Where inside of the traditional Update, each item takes care of its own Input-handling/Movement/Model-Updating/Spritesheet-Animation/AI/et cetera, you're updating each subsystem one after another, and each subsystem is going through each entity which has a registered component in that subsystem, one after another.
So there's a smaller memory-footprint on the number of unique functions.
But it's a very different universe in terms of thinking about how to do it.
I am learning more advanced OO tactics for javascript coming from a C# background and am wondering about how to or if its even a good idea to implement prototype based validation. For instance when an object or function requires one of its parameters to satisfy a certain interface, you could check its interface like so,
var Interface = function Interface(i) {
var satisfied = function (t, i) {
for (var key in i) {
if (typeof t !== 'object') {
return false;
}
if (!(key in t && typeof t[key] == i[key])) {
return false;
}
}
return true;
}
this.satisfiedBy = function (t) { return satisfied(t, i); }
}
// the interface
var interfacePoint2D = new Interface({
x: 'number',
y: 'number'
});
// see if it satisfies
var satisfied = interfacePoint2D.satisfiedBy(someObject);
I came up with this strategy to validate an object by its interface only, ignoring the internal implementation of the object.
Alternatively say you are using prototype-based inheritance, should you or should not validate parameters based on their prototype functions? I understand that you'd use a prototype to implement default functionality whereas an interface doesn't specify any default functionality. Sometimes the object you are passing into a function might need certain default functionality in order for that function to work. Is it better to only validate against an interface, or should you ever validate against a prototype, and if so, whats the best way to do it?
EDIT -- I am providing some more context as to why I am asking this,
Say for instance in online game design (games written mostly in javascript). There are 2 main reasons I am interested in validation within this context,
1) Providing a strong public API for modding the game if desired
2) Preventing (or atleast discouraging greatly) potential cheaters
Which requires a balance between customizability and abuse. Specifically one situation would be in designing physics engine where objects in the game react to gravity. In a realistic system, users shouldn't be able to add objects to the system that do not react to gravity. The system has a function that expresses the global effect of gravity at any given point:
function getGravityAt(x, y) {
// return acceleration due to gravity at this point
}
And objects which react have a method that uses this to update their acceleration:
function update() {
this.acceleration = getGravity(this.position);
}
The minimum thing to do might be to ensure that any object added to the system has an 'update' method, but you still aren't ensuring that the update() method really is intended to react to gravity. If only objects that inherit from a prototypical update() method are allowed, then you know at least to some degree everything in the system reacts realistically.
This is a pretty subjective question. I'll pass on the question of whether it's a good idea to do interface-based validation in Javascript at all (there may well be good use-cases for it, but it's not a standard approach in the language). But I will say that it's probably not a good idea to validate objects based on their prototypes.
If you're validating by interface at all, you're probably working with objects created by other programmers. There are lots of ways to create objects - some rely on prototypes, some do not, and while they each have their proponents, they're all valid and likely approaches. For example:
var Point = function(x,y) {
return {
x: function() { return x },
y: function() { return y }
};
};
var p = new Point(1,1);
The object p conforms to an interface similar to yours above, except that x and y are functions. But there's no way to validate that p satisfies this interface by inspecting its constructor (which is Object()) or Point.prototype. All you can do is test that p has attributes called x and y and that they are of type "function" - what you're doing above.
You could potentially insist that p has a specific ancestor in its prototype chain, e.g. AbstractPoint, which would include the x and y functions - you can use instanceof to check this. But you can't be sure that x and y haven't been redefined in p:
var AbstractPoint = function() {};
AbstractPoint.prototype.x = function() {};
AbstractPoint.prototype.y = function() {};
var Point = function(x,y) {
var p = new AbstractPoint(x,y);
p.x = "foo";
return p;
}
var p = new Point(1,1);
p instanceof AbstractPoint; // true
p.x; // "foo"
And perhaps more importantly, this makes it harder to drop in custom objects that also satisfy the interface but don't inherit from your classes.
So I think what you're currently doing is probably the best you can hope for. In my experience, Javascript programmers are much more likely to use on-the-fly duck-typing than to try to mimic the capabilities of statically typed languages:
function doSomethingWithUntrustedPoint(point) {
if (!(point.x && point.y)) return false; // evasive action!
// etc.
}
I'll reiterate, type checking is not idiomatic javascript.
If you still want type checking, Google's closure compiler is the implementation I recommend. Type checking is done statically :) It has conventions for interfaces as well as (proto)type checking.