Extending a javascript object - javascript

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

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'

Subclass of a Subclass?

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.

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() )

Understanding Classes and Inheritance in Javascript - New Pattern

I'm designing an OOP inheritance pattern for many applications I'm building. Javascript has many ways of doing this, but I stumbled on a pattern I really like. But now I'm struggling with the need for a separation of classes and instances.
I have a base object called Root. And it has a main method called inherit. To create a new object you use
var Person = Root.inherit({
name : "",
height : 0,
walk : function() {},
talk : function() {}
});
Then to create an "instance" you would
var sally = Person.inherit({
name : "sally",
height : "5'6"
});
sally can .talk() and she can walk() and she has a .name and a .height
You can make more people the same way.
If you want a constructor you use
var Person = Root.inherit({
_construct : function() {
// do things when this object is inherited from
},
name : "",
height : 0,
walk : function() {},
talk : function() {}
});
It also has the ability to have init, when the object is first defined in code (singletons use this)
var Person = Root.inherit({
_init : function() {
// called at runtime, NOT called if an object is inherited from me
},
name : "",
height : 0,
walk : function() {},
talk : function() {}
});
So as you can see, everything uses .inhert(). There are no classes and no instances really. Everything is an instance of something. The only real problem I found so far is that there is no concept of "type", but you can always just check for a method if you need to. Also you can't protect a 'class', as a 'class' can be changed during execution if the developer accidentally changed it, or meant to change it.
So my question is: Is there a need in javascript to have an explicitly and controlled separation of class structure and instances of the class? Are there any issues with treating every object as an instance?
No there's no need since Javascript is a Prototypal based language, meaning that classes are not involved. You are just creating clones of the objects.
http://en.wikipedia.org/wiki/Prototype-based_programming
As far as the concept of type, the type is object.
A good read for more info about this would be Javascript Patterns by Stoyan Stefanov he has several different creational patterns that address your concerns, including examples that implement Design Patterns from the gang of four's design patterns.
http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752
So my question is: Is there a need in javascript to have an explicitly and controlled separation of class structure and instances of the class? Are there any issues with treating every object as an instance?
Not really, if you're happy with it, it's fine.
The more normal form of JavaScript inheritance does much the same thing. You'll frequently see structures like this (severely cut down for brevity):
function Base() {
}
Base.prototype.foo = function() {
};
function Derived() {
}
Derived.prototype = new Base();
...and of course, new Base() is also how you create instances of Base. So your system is quite similar.
Again, the above is a sketch, not a full example. For one thing, usually you'd see construction and initialization separated out, so you don't literally see Derived.prototype = new Base() so much as something that creates an object with Base's prototype but without actually calling Base (which Derived would do later), but you get the idea. Granted that statement somewhat weakens the similarity with your system, but I don't think it breaks it at all.
At the end of the day, it's all about objects (instances), which are either used directly (your sally) or indirectly by providing features to other objects (Person, Root) by cloning or by setting them up as the prototype of the other object.
Javascript's inheritance is prototypical which means everything object is an instance. You actually have to do extra work to get the classical inheritance.
This is how I work in javascript
// this is class
function person(){
// data is member variable
this.name = null;
this.id = null;
//member functions
this.set_name = _set_name;
this.get_name = _get_name;
this.set_id = _set_id;
this.get_id = _get_id;
function _set_name(name){
this.name = name;
}
function _get_name(name){
return this.name;
}
function _set_id(id){
this.id = id;
}
function _get_id(id){
return this.id;
}
}
// this is instance
var yogs = new person();
yogs.set_id(13);
yogs.set_name("yogs");
hope it may help
Start with some basic object...
// javascript prototypes - callback example - javascript objects
function myDummyObject () {
that = this;
} // end function myDummyObject ()
// begin dummy object's prototype
myDummyObject.prototype = {
that : this,
// add a simple command to our dummy object and load it with a callback entry
say : function () {
var that = this;
console.log('speaking:');
that.cb.run("doSay");
}
} // end myDummyObject proto
extend with a sub prototype..
// here we addon the callback handler... universally self sufficient object
var cb = {
that : this, // come to papa ( a link to parent object [ myDummyObject ] )
jCallback : new Array(new Array()), // initialize a javascript 2d array
jCallbackID : -1, // stores the last callback id
add: function(targetFnc, newFunc) {
var that = this;
var whichID = that.jCallbackID++;
// target, addon, active
that.jCallback[that.jCallback.length] = { 'targetFunc' : targetFnc, 'newFunc' : newFunc, 'active' : true, 'id': whichID };
return whichID; // if we want to delete this later...
}, // end add
run: function(targetFnc) {
var that = this;
for(i=0;i <= that.jCallback.length - 1;i++) // go through callback list
if( that.jCallback[i]['targetFunc'] == targetFnc && that.jCallback[i]['active'] == true )
that.jCallback[i]['newFunc'](); // run callback.
}, // end run
remove: function (whichID) {
var that = this;
console.log('removing:' + whichID);
for(i=0;i <= that.jCallback.length - 1;i++) // go through callback list
if( that.jCallback[i]['id'] == whichID )
that.jCallback[i]['newFunc'](); // run callback.
} // end remove
}
// add the object to the dummy object...
myDummyObject.prototype.cb = cb;
Example:
var testing = new myDummyObject();
testing.cb.add('doSay', function () { console.log('test: 213123123'); } );
// test remove...
var testid = testing.cb.add('doSay', function () { console.log('test: 12sad31'); } );
testing.cb.remove(testid);
testing.cb.add('doSay', function () { console.log('test: asdascccc'); } );
testing.cb.add('doSay', function () { console.log('test: qweqwe'); } );
testing.cb.add('doSay', function () { console.log('test: d121d21'); } );
testing.cb.add('doSay', function () { console.log('test: wwww'); } );
testing.say();
This always seemed the easiest for me to understand... Just create a new instance of the inherited class and then loop through its variables and methods and add them to the main one.
var myPerson = new Person()
var myPerson.firstName = 'john';
var myPerson.lastName = 'smith';
var myPerson.jobTitle = 'Programmer';
var Person = function(){
//Use this to inherit classes
this._extendedClass = new Person_Job();
for(var i in this._extendedClass){
this[i] = this._extendedClass[i];
}
delete this._extendedClass;
this.firstName = '';
this.lastName = '';
}
var Person_Job = function() {
this.jobTitle = '';
}

JavaScript class memory usage

So I've been doing some JavaScript class-like stuff such as
MyClass = function()
{
var x;
this.sayX = function()
{
alert(x);
}
}
but I've also seen
MyClass = function()
{
this.x = 0;
}
MyClass.prototype.sayX = function()
{
alert(this.x);
}
The big question is, am I still wasting memory space in today's JavaScript engines, or are they capable of seeing the duplication in my method and optimizing them out? The reason I ask is because I'd rather do proper data hiding and not have to prefix absolutely everything with 'this'.
The memory footprint of the first one will always be larger. Consider prototype as a shared package of methods that all instances can use. It is effective because you don't create a new function for every instance, but you're reusing the existing method already in memory.
The good news is that the two ways you showed can be combined.
MyClass = function () {
var x;
// public method with access
// to private variables
this.sayX = function () {
alert(x);
};
}
// method that doesn't need access to private variables
MyClass.prototype.sharedMethod = function () {
// ...
}
But as far as you're dealing with small codebase, you shouldn't worry about memory usage. You can even use patterns like
// everything will be created for every
// instance, but the whole thing is nicely
// wrapped into one 'factory' function
myClass = function () {
// private variables
var x;
// private methods
function doSomethingWithX() {}
// public interface
return {
sayX: function () {
alert(x);
},
publicMethod: function () { .. },
// ...
};
};
Note, I intentionally changed myClass to lowercase, because it's no longer a constructor function and there's no need to use new when invoking!
UPDATE - there's a third pattern which well suits your needs:
MyClass = function (x, y, whatever) {
this._init.apply(this, arguments);
}
// The prototype creates a scope for data hiding.
// It also includes a constructor function.
MyClass.prototype = (function () {
var x; // private
return {
_init: function (x_in) {
x = x_in;
},
sayX: function () {
alert(x);
},
// ...
};
})();
Revisiting this a huge amount later, but it turns out V8 is smart enough that it doesn't create multiple instanced of that function in the first method. Go hidden classes :D
http://www.youtube.com/watch?v=hWhMKalEicY

Categories

Resources