Subclass of a Subclass? - javascript

I've been writing a game engine, and I wanted to re-organize my code to make it more modular. Currently, I have a main function called Isometric that accepts the canvas to draw.
var iso = new Isometric('canvas');
So far so good. Next, I had .newMap() to create a new map.
var map = iso.newMap(10,1,10); // Creates 10x1x10 map
However, I want to change that since there might be some confusion with the .map property (since this returns an array called map).
I wanted the syntax to look like this:
iso.Map.create(10,1,10);
So I tried something like this:
function Isometric(id) {
this.Map = function() {
this.create = function() {
}
}
}
But when I went to access it, I realized that the second level of this still refers to the same first level this. So, I can't create a sub-class of the Map object.
I've looked at a few different methods, but none of them had clear examples and I couldn't get them to work.
Among them, I'm aware that you can use prototype, and Object.create() but I've not gotten much success.
How can I do this?
The other solution I have is to do something like this:
function Isometric('id') {
this.Map = {
'create': function() { },
'load': function() {}
}
}
and then access it like
iso.Map['create'];
but I don't like that at all. Any clean methods of doing it?
My main interest is an example with the third-level method ..create() inside .map. If you could provide me with documentation related to my question that I have not yet found, that would be nice. But even mozilla docs didn't seem to help.

I think the appropriate thing to do here is to namespace your Map constructor under the Isometric constructor. Here is how you could go about it.
function Isometric(id) {
this.id = id;
}
Isometric.prototype = {
constructor: Isometric,
test: function() {
return "I'm an instance of Isometric.";
}
};
Here we do the namespacing and add a create() helper method to the Map constructor to create its instances.
Isometric.Map = function Map(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
Isometric.Map.prototype = {
constructor: Isometric.Map,
test: function() {
return "I'm an instance of Isometric.Map.";
}
};
// Helper method to create `Map` instances
Isometric.Map.create = function create(x, y, z) {
return new Isometric.Map(x, y, z);
};
Usage:
var iso = new Isometric('id123');
var map = new Isometric.Map(0, 7, 99);
var map2 = Isometric.Map.create(1, 2, 3);
iso.test(); //=> "I'm an instance of Isometric."
map.test(); //=> "I'm an instance of Isometric.Map."
map2.test(); //=> "I'm an instance of Isometric.Map."
Namespaces
It's important to note that the namespacing we just did prevents collisions with the new Map class in ES6 (new JS version) - more about ES6 Maps here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map.
With that said, it's always important to namespace your code under one main object (you could call it app) and only make that namespace available globally.
In your case you could do something like the following example:
;(function(win) {
// Isometric
function Isometric(id) {
this.id = id;
}
Isometric.prototype = {
constructor: Isometric,
test: function() {
return "I'm an instance of Isometric.";
}
};
// Map
function Map(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
Map.prototype = {
constructor: Map,
test: function() {
return "I'm an instance of Isometric.Map.";
}
};
// Helper method to create `Map` instances
Map.create = function create(x, y, z) {
return new Map(x, y, z);
};
// Namespace Map under Isometric
Isometric.Map = Map;
// Expose globally
// --------------------
win.app = {
Isometric: Isometric
};
}(this));
Example:
var nativeMap = new Map();
nativeMap.set('name', 'joe'); //=> {"name" => "joe"}
var myMap = new app.Isometric.Map(33, 7, 99);
myMap.test(); //=> "I'm an instance of Isometric.Map."
// Native map wasn't affected (good)
nativeMap.test(); //=> TypeError: undefined is not a function

I will leave the other answer as accepted because it was more detailed and even told me about my code possibly becoming deprecated as is.
That being said, I want to re-iterate Felix King's solution. I will figure a way of combining both ideas (using namespaces and using Felixs) but here's what the partial solution was.
function Isometric(id) {
this.Map = function() {
this.create = function() {
return 5;
};
};
}
That was the set up I had. 5 is just an arbitrary value.
var iso = new Isometric(); // New instance of Isometric()
var mapping = new iso.Map(); // Access to Iso's mapping functions
var map = mapping.create(); // Should return a map array
console.log(map); // Prints 5
For anyone following along on this, if you want to see how I end up implementing it, then see my Github project: https://github.com/joshlalonde/IsometricJS
I'll play around with the code in sometime this weekend.
Again, thanks for your help everyone! Good luck to anyone trying to do something similar.

Related

How to handle several instance on the same Class in a plugin?

I have a JS plugin using es6 class syntax. I'm not sure on the way to handle several instances of the class versus once instance with a several element inside.
This plugin can have an array an unlimited number of image nodes as parameters.
This is the class syntax I have so far
(function(window) {
function handle(element, options) {
let handles = [];
if (element.length) {
for (var i = 0; i < element.length; i++) {
handles.push(new Plugin(element[i], options));
}
} else {
handles.push(new Plugin(element, options));
}
return handles;
}
class Plugin {
constructor(element, options) {
this.element = element;
this.init();
}
init() {
//get its translated value
this.methodA();
//apply its translation even if not visible for the first init
this.methodB();
}
methodA() {
this.element.classList.add('test');
}
}
return handle;
});
I would like to get rid of this handle function. What is the other way to have an instance of plugin for every element? and to be able to have the classPlugin at the top level without the need for this handle function.
I don't see any other way that having several instances of the class, because each instance get specified info for each image (height, offset, etc). Maybe I am missing something obvious here...
You can't actually instantiate an instance of a class without a loop. You may try eval. But it's not recommended. It's a bad practice.
Now let me explain why it is not possible.
JavaScript does not have classes and instances, it has only objects, which can delegate to other objects.
To create two objects based on a single object, but behind the scenes, there aren’t really two ‘instances’ of the Point object, there are just two objects that delegate to the original one. When you use new, JavaScript is actually just creating an object and setting its prototype to the object returned by the constructor function. Imagine if the example had been expanded to include a shared method like this:
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.logCoords = function () {
console.log(this.x, this.y);
};
var a = new Point(1, 2);
console.log(a.x); // logs '1'
a.logCoords(); // logs '1 2'
Behind the scenes, what’s happening is something more like this:
var Point = function (x, y) {
this.x = x;
this.y = y;
};
Point.prototype.logCoords = function () {
console.log(this.x, this.y);
};
var a = {};
a.__proto__ = Point.prototype; // see note below about this
a.constructor = Point;
a.constructor(1, 2);
console.log(a.x); // logs '1'
a.logCoords(); // logs '1 2'

Creating javascript functions when needed

I'm trying to determine the performance implications of some javascript. In our application, a form contains a number of widgets. Not all widgets are used on every page or a widget might be used more than once. I've been thinking about a model similar to the following (note that the actual script is a lot more complicated, I've simplified it to be brief):
var widget = {
type1: function(args) {
function getName() {
return this._name;
}
return (widget.type1 = function(args) {
return {
_name: args.name,
getName: getName
};
})(args);
}
}
My thought is that the first time the widget.type1 function is called, it will initialize all the code needed for a widget.type1. Any subsequent widget.type1 would then use the functions. I know that I could do something like this:
var widget = {
type1: function(args) {
return {
_name: args.name,
getName: function getName() {
return this._name;
}
};
}
}
But then each type1 object would have it's own copy of a function that does the same thing, which I would assume would use more memory (I've tested in browser debugging tools that o1.getName != o2.getName).
I could just write out the script for the types of widgets that are on the current page from the server, but then I don't benefit from caching a single js file and I don't want to put each widget in its own js file because then it would have to download them all separately.
Will this result in problems? Would/should this perform as I think? Other thoughts?
Edit
I think I should explain my reasoning. My thought (which could be erroneous) is that the first time a widget is used, it would initialize the logic used by the widget. For instance, if I never create a type1 widget, there's no need to add a bunch of functions to the prototype of the type1 widget. The code I wrote was highly simplified. There may be 500+ lines of code used by that widget, and I'm not actually using a getName function, that was just an example. If the widget isn't used, it wouldn't need that logic at all. It also keeps functions only used by that widget out of the global scope.
I'm currently using objects and adding functions to the prototype of that object (e.g. MyType.prototype.whatever = function(){ ... }), but the thought occurred to me that if I never create an object of MyType, why bother initializing the prototype of MyType?
Another way to do what I'm thinking, this time using object prototypes (again, there might be 300 functions added to the prototype of type1. The idea I'm asking is if it makes any sense at all to not go ahead and add them to the prototype of type1 if a type1 is never created):
var widget = {
_type1Init: function()
{
widget.type1.prototype.getName = function() {
return this._name;
}
widget._type1Init = function(){} //So calling again won't do anything.
},
type1: function(args) {
widget._type1Init();
this._name = args.name;
}
}
if(*someCondition*)
var obj = new widget.type1({ name: "hello world" }); // If an object is created, it gets initilized, otherwise it won't.
Maybe you should consider:
function type1(argObj){
// use arguments Array for all arguments - you have Object notation
this._name = argObj.name;
// not sure why you need this function
this.getName = function(){
return this._name;
}
}
function widget(){
this.type1 = type1;
}
I'm not really sure what you want to achieve, but I think this is a case for prototype
var widget = {
type1: function(args) {
this._name = args.name;
}
};
widget.type1.prototype.getName = function() {
return this._name;
}
var w1 = new widget.type1({ name: 'Alice' });
console.log(w1.getName());
var w2 = new widget.type1({ name: 'Bob' });
console.log(w2.getName());
See JSFiddle
Personally, I'd consider... not necessarily a whole restructure, but if your module/widget has:
a) known "private static" functions (utilities or stateless transformers) that you want to reuse
b) functions which must operate on instance-specific state
Then you're in the market for an IIFE.
{
widget_1 : (function () {
var private_static_method = function (a, b, c) {
}; // no access to instance-based, closure state, unless passed as arguments
return function (d, e, f) {
// d, e and f are currently private, instance-based values (closure-scope)
this.public_method = function () { // this is copied per-instance
// has full access to d, e, f
return private_static_function(d, e, f);
};
this.g = d;
};
}())
}
widget_1 is the returned function.
The constructor which is widget_1 now has private-static access (closure) to whatever is INSIDE the wrapping function, but OUTSIDE of the constructor.
So there's only one copy, with the caveat that the static functions have no sight into any private state (closure) of any instance.
Moreover, taking this one step further would indeed allow you to break up your JS into individual files (which you could build back into one file safely) and have your object work exactly the same way on the other side.
// core-file.js
var my_widgets = {};
// widget-1.js
(function (core) {
var private_static_method = function () { };
// ...
core.widget_1 = function (d, e, f) { };
}(my_widgets));
You can then recombine all of your files and access them just like before, on the other side.
var widget_1a = new my_widgets.widget_1(a, b, c);
If you have absolutely no private state, then rather than the "private static" stuff above, what you can do inside of your IIFE is define a constructor function, and add prototypes to it (these are "public-static", with no access to private state).
widget_1 : (function () {
var Widget_1 = function (d, e, f) { this.g = d; };
Widget_1.prototype.add_one = function () { this.g += 1; };
return Widget_1;
)())
var w1 = new my_widgets.widget_1(x, y, z);
w1.add_one();
w1.g; // == x+1
A combination of enclosed utility functions, enclosed per-instance state, extended prototype functions, et cetera, will allow you to do everything you want, from lowering memory-footprint (I hope you have thousands of these before worrying about this), to chaining together super-secure (higher-memory-usage) objects.
note although doing crazy closure stuff might be secure, client-side code (or, more-especially, the http(s?) bridge between the worlds is very much not...
If a widget is used more than once, than the object/prototype model will conserve memory.
something like this:
var wid = {}
wid.objInit=function(p) { this.p=p }
wid.objInit.prototype.doit=function(){ return this.p + ' it'}
wid.init=function(arg){
var w = new wid.objInit(arg)
return w
}
The prototype is written once, placed into memory once and each object instance can call it.
var w = wid.init('do')
console.log( w.doit() )
var w2 = wid.init('do')
console.log( w2.doit() )

Extending a javascript object

I'm currently working on a platform game engine using javascript and the HTML5 canvas.
I have an object, "platform" which looks something like this...
var platform = function(pid,px,py,pw,ph) {
//Some variables here... and then we have some functions
this.step = function() {
//Update / step events here
}
this.draw = function() {
//Drawing events here
}
//etc.
}
The step() function has all of the calculations for collision detection while the draw() function draws the platform.
What I want to do is make another object called movingPlatform. This will be almost identical to the current platform except for the fact this one moves.
Rather than copying all of the collision detection code I'd like to be able to extend movingPlatform from platform... and then be able to add some additional code into the step() function to the moving platform can... well... move.
Some additional information...
When the game loads, it generates the level using data from a CSV file. I have an array, platforms[] that stores all of the platforms within it.
So to create a platform it looks like this...
platforms.push(new platform(i,data[1],data[2],data[3],data[4]));
I then make the platforms perform their step and draw events during the game's main step and draw events.
i.e.
for(var i=0; i<platforms.length; i++) {
platforms[i].step();
}
Any help would be awesome. Thanks!
I would use the platform class as a "base" object for the moving platform object.
I would do this via the prototype which is JavaScript's implementation of object oriented programming.
More info here How does JavaScript .prototype work?
+ many more articles on the web
You can use Javascript prototype inheritance functionality:
var baseItem = {
push: function(){alert('push');},
pull: function(){alert('pull')}
}
var childItem = {}
childItem.prototype = baseItem;
childItem.push = function(){
//call base function
childItem.prototype.push.call(this);
//do your custom stuff.
alert('I did it again.');
}
childItem.push();
Fiddle
Rather than pure inheritance, here, I'd go with prototype-extension, unless you build some big, ugly factory, just for the sake of saying that "MovingPlatform" inherited from "Platform" in a pure sense, it's not really what you'd expect it to be.
There are a few concerns (cheating, for one), but if your objects are all based wholly around this, and you're okay with people potentially hacking away in the console, then you don't really have much to worry about.
First, understand what you're doing inside of Platform:
var MyObject = function (a) {
this.property = a;
this.method = function (b) { this.property += b; };
};
Every time you make a new MyObject, you're creating a brand new version of the .method function.
That is to say, if you make 10,000 of these, there will be 10,000 copies of that function, as well.
Sometimes that's a very good and safe thing.
It can also be a very slow thing.
The problem is, because everything in your object is using this, and because nothing inside of the function changes, there's no benefit to creating new copies -- just extra memory used.
...so:
MyObject = function (a) {
this.property = a;
};
MyObject.prototype.method = function (b) { this.property += b; };
var o = new MyObject(1);
o.method(2);
o.property; //3
When you call new X, where X has properties/methods on its prototype, those properties/methods get copied onto the object, during its construction.
It would be the same as going:
var method = function (b) { this.property += b; },
o = new MyObject(1);
o.method = method;
o.method(2);
o.property; // 3
Except without the extra work of doing it yourself, by hand.
The benefit here is that each object uses the same function.
They basically hand the function access to their whole this, and the function can do whatever it wants with it.
There's a catch:
var OtherObj = function (a, b) {
var private_property = b,
private_method = function () { return private_property; };
this.public_property = a;
this.unshared_method = function () { var private_value = private_method(); return private_value; };
};
OtherObj.prototype.public_method = function () {
return private_property;
};
var obj = new OtherObj(1, "hidden");
obj.public_property; // 1
obj.unshared_method(); // "hidden"
obj.public_method(); // err -- private_property doesn't exist
So assuming you don't have much you care about staying private, the easiest way of doing this would be to make reusable function, which rely on this, which you then give to multiple prototypes, through extension.
// collision-handling
var testCollision = function (target) { this./*...*/ },
handleCollision = function (obj) { this./* ... */ };
// movement-handling
var movePlatform = function (x, y, elapsed) { this.x += this.speed.x*elapsed; /*...*/ };
// not really the cleanest timestep implementation, but it'll do for examples
var Platform = function (texture, x, y, w, h) {
this.x = x;
// ...
},
MovingPlatform = function (texture, x, y, w, h, speedX, speedY, etc) {
this.etc = etc;//...
};
Platform.prototype.testCollision = testCollision;
Platform.prototype.handleCollision = handleCollision;
MovingPlatform.prototype. // both of the above, plus the movePlatform method
This is a lot by hand.
That's why functions in different libraries will clone or extend objects.
var bunchOfComponents = {
a : function () { },
b : 32,
c : { }
},
myObj = {};
copy(myObj, bunchOfComponents);
myObj.a();
myObj.b; //32
Your function-reuse goes up, while the horror of writing proper Class-based, hierarchical inheritance, with virtual-overrides, abstracts, and shared-private properties, by hand, goes down.
Getting inheritance right in Javascript is somewhat tricky if you're used to class-based languages.
If you're not sharing a lot of behaviours, you might find it easier to just create some shared methods, then make them available to objects of each platform type.
//Create constructors for each type
var Platform = function(pid,px,py,pw,ph) { //By convention, constructors should start with an uppercase character
...
}
var MovingPlatform = function() {
...
}
//Create some reuseable methods
var step = function() {
...
}
var draw = function() {
...
}
var move = function() {
...
}
//Attach your methods to the prototypes for each constructor
Platform.prototype.step = step;
Platform.prototype.draw = draw;
MovingPlatform.prototype.step = step;
MovingPlatform.prototype.draw = draw;
MovingPlatform.prototype.move = move;
...etc
That said, if you do want to build up a proper inheritance chain, there are plenty of articles available to help you: 1 2 3 4

How to add context methods to an object

I'm making a library for math graphing in canvas, and before, my approach was to directly add methods to the global context prototype, as such
CanvasRenderingContext2D.prototype.point=function(x,y){
this.fillRect(x,y,1,1);
};
However, I found out that that was not recommended, so what I'm trying now is to make a global object, as such
window.Graph=function(context){
this.ctx=context;
alert(this.ctx);
this.CanvasRenderingContext2D.prototype.point=function(x,y){
this.ctx.fillRect(x,y,1,1);
};
};
I have also tried
this.ctx.prototype.point=function(x,y){
this.ctx.fillRect(x,y,1,1);
};
All of them return errors like cannot set property 'point' to undefined
The ideal way to call it would be
var g=new Graph(ctx);
g.point(5,5);
What would be the best way to do this?
Thanks
Here's what you are looking for:
function Graph(context) {
this.context = context;
}
Graph.prototype.point = function (x, y) {
this.context.fillRect(x, y ,1, 1);
}
var g = new Graph(context);
g.point(5, 5);
plalx shows a great design pattern...
Here's just another with a constructor:
var Graph = (function () {
// constructor
function Graph(context) {
// "class" properties go here
this.context = context;
}
// "class" methods added to prototype here
Graph.prototype.point = function (x,y) {
this.context.fillRect(x,y,1,1);
};
// return a self reference
return Graph;
})(); // make class available by self-executing
// instantiate your Graph class into a graph object
var graph = new Graph(context);

Collection/Instance objects style vie javascript without proto

I'm trying to make classical Collection/Instance model via javascript. So Collection object has some method for working with full collection and ((new Collection()) instanceof Instance) has methods to work with the instance. My code is rather simple.
var Collection = function Collection() {
this.message = "collection";
var I = Instance.bind(null, this);
I.__proto__ = this;
return I;
};
Collection.prototype = {
collectionMethod: function () {
console.log(this.message);
}
};
var Instance = function Instance(collection) {
this.collection = collection;
this.message = "instance";
};
Instance.prototype = {
instanceMethod: function () {
console.log(this.message);
}
};
// Test exec (values are like expected);
var C = new Collection();
var i = new C();
C.collectionMethod(); // collection
i.instanceMethod(); // instance
i.collection.collectionMethod(); // collection
C.newMethod(); // TypeError
i.newMethod(); // TypeError
Collection.prototype.newMethod = Instance.prototype.newMethod = function () {
console.log("newMethod: " + this.message);
}
C.newMethod(); // newMethod: collection
i.newMethod(); // newMethod: instance
But i don't want to use proto because it's not a part of standart and doesn't work in IE at all. Is there any way around in this case?
Some explanations about what's all about. For example you have a collection of users. And you want to be able find the user and create new one.
So you create new collection like
var User = new Collection();
Then you create new instance like.
var me = new User({name: "alex"});
And now you find this instance like
User.find_by_name("alex"); // === me
Also (in fact this is the main reason i'm doing this way instead of just creating something like User.new function to use it like var me = User.new({name: "alex"});) you can know who I am doing something like (if you for example have also var Dog = new Collection())
me instanceof Dog // false
me instanceof User // true
This code:
var I = Instance.bind(null, this);
I.__proto__ = this;
return I;
really doesn't make much sense. Function.bind creates a new function, so anyone calling your Collection function, in any way, will get back a function, not an object whose prototype is set to the function's prototype.
In general, if you want to create an object whose prototype is set to a specific object, you don't set __proto__ since that's not standard, as you stated. The best way is to just use Object.create (which is shimable if you want to support IE8).
var I = Object.create(this);
Also, the reason you're getting errors on newMethod is because you're trying to call them before you add them to the prototype:
Collection.prototype.newMethod = Instance.prototype.newMethod = function () {
console.log("newMethod: " + this.message);
}
C.newMethod(); // should work now
i.newMethod(); // should work now
So seems like it's impossible for now. More information can be found here.
How do I inherit javascript functions ?

Categories

Resources