Using JSON notation, how do I create a public method in javascript? - javascript

In this example:
var circle = {
radius : 9,
getArea : function()
{
return (this.radius * this.radius) * Math.PI;
}
};
from this page's Encapsulation topic, the getArea is private, how would be with it public?

That's not JSON notation, that's JavaScript object literal notation. (JSON is a subset of object literal notation. It doesn't allow functions, requires double quotes, and doesn't support octal or hex.)
getArea isn't private, anything can call it. The page you quoted is simply incorrect. If you want patterns for truly private methods in JavaScript, here's a roundup with desciptions of the various trade-offs (including the memory cost of the Crockford model, which is the most common form).

As T.J. Crowder says... that's not JSON. I think maybe the problem is that the getArea property of your circle object is being set to whatever the getArea function returns. Which means that circle.getArea() won't work because circle.getArea is a number. This is wrong but I think its a step closer to what you are trying to achieve (I'll show a better way after this):
var circle = {
radius : 9,
getArea : function(){
return Math.PI * 9 * 9;
}
};
alert(circle.radius);
alert(circle.getArea());
The important thing above is to note the way I define the getArea function inside the object. This can be useful, but the problem is that the get area function doesn't have access to the radius variable, because objects like circle don't have their own scope. If you try :
var myObj = {test:this};
alert(myObj.this);
You'll see [object DOMWindow]
So how do you create an object Circle with a radius property and a getArea method? There are a many ways. One way is like this:
function Circle(r){
var c = this;
this.radius = r;
this.getArea = function(){
return Math.PI * c.radius * c.radius;
}
}
var circle = new Circle(10);
document.write(circle.getArea()+"<br/>");
circle.radius = 20;
document.write(circle.getArea()+"<br/>");
var otherCircle = new Circle(1);
document.write(otherCircle.getArea()+"<br/>");
I've created a jsFiddle of the above.
This can also be achieved using prototype property:
function Circle(r){
this.radius = r;
}
Circle.prototype.getArea = function(){
return Math.PI * this.radius * this.radius;
}
var circle = new Circle(10);
document.write(circle.getArea()+"<br/>");
circle.radius = 20;
document.write(circle.getArea()+"<br/>");
var otherCircle = new Circle(1);
document.write(otherCircle.getArea()+"<br/>");

There are no such thing as private method or property in javascript.
Everyting is public but common practise is to treat anything beginning with _ as private, but thats only convention, not enforced byt the language.
To have private methods and properties you need real classes to define them and javascript does not have real classes.

Related

I can't seem to access a object's prototype method in Phaser with a custom tile object. What am I doing wrong?

I am extending a basic Sprite object in Phaser to include some additional functions, mainly the ability to switch the textures with shortcut words. However, when I try to access the method, I get
"hex.switchSprite is not a function"
After some basic research, most of the answers are saying to include .prototype - however.. it's already in the method. This is the object itself that I have so far. Everything in switchSprite has been removed for testing purposes:
hexTile = function(game, x, y)
{
Phaser.Sprite.call(this, game, x, y, 'masterTileSheet', 'Gemstone_Missing');
this.scale.x = 0.75;
this.scale.y = 0.75;
this.anchor.x = 0.5;
this.anchor.y = 0.5;
}
hexTile.prototype.switchSprite = function(name)
{
}
hexTile.prototype = Object.create(Phaser.Sprite.prototype);
hexTile.prototype.constructor = hexTile;
I followed the example set out in the Phaser docs, and when I don't use switchSprite, it works:
var hex = new hexTile(game, 0, 0);
var point = calculateGrid(x,y);
hex.x = point.x;
hex.y = point.y;
gameContainer.add(hex);
//console.log(returnRandomHex());
hex.switchSprite();
The above is how I'm accessing and running it - it should be right, but for switchSprite I just get the above error.
An observation: you're overwriting your prototype:
hexTile.prototype.switchSprite = function(name)
{
}
hexTile.prototype = Object.create(Phaser.Sprite.prototype);
You set the prototype of hexTile after you added the switchSprite function to it. Try switching the order of these two statements.

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.

Javascript Class/Static Variables

I'm learning Javascript from Head First Javascript (Morrison).
In one example, the author declares a variable 'signature' to be a class property of a class called Blog by doing the following:
Blog.prototype.signature = "by Blogger-Name";
Is there difference between the above and declaring it like how I have below?
Blog.signature = "by Blogger-Name";
All instances of Blog will have signature when you using .prototype. So when you instantiate var blog = new Blog. It will have a signature property.
If you were to just use Blog.signature = x Then when you create an object with new it wouldn't be there.
Setting a property of a prototype member of a constructor makes the property visible (when reading) from all instances.
This can be done to emulate static members of C++ classes and is often done in Javascript form methods (because methods are indeed just regular data members, differently from C++).
One example where this could be used instead for "data" is keeping all instances of a certain "class" in a container:
function Widget(x0, y0, x1, y1, name) {
this.x0 = x0;
this.y0 = y0;
this.x1 = x1;
this.y1 = y1;
this.name = name;
this.all_instances.push(this);
}
Widget.prototype.all_instances = [];
var w1 = new Widget(10, 20, 30, 40, "First");
var w2 = new Widget(10, 20, 30, 40, "Second");
Note that however when writing to such a "static" property you're creating instead an instance property; push works because it's not writing to .all_instances but modifying its content (the array).

Constructor methods in javascript affect all instances of object

I'm working on an implementation of tetris to teach myself javascript and I've run into a problem. First, the background: I have a class for each type of tetris block that inherits from a basic block template with methods like moving and returning coordinates. For instance,
function BlockTemplate(w, h, c){
var height = h;
var width = w;
var x = 0;
var y = 0;
var color = c;
this.getHeight = function(){return height;};
this.getWidth = function(){return width;};
this.getX = function(){return x;};
this.getY = function(){return y;};
this.getColor = function(){return color;};
this.moveTo = function(newX, newY){
x = newX;
y = newY;
};
this.translate = function(dx, dy){
x += dx;
y += dy;
};
}
function StraightBlock(){
this.draw = function(){
ctx.fillStyle = this.getColor();
ctx.fillRect(this.getX(), this.getY(), 20, 100);
};
}
StraightBlock.prototype = new BlockTemplate(20, 100, "#00FFE5");
All blocks currently on the screen are stored in an array, blockArr, except for the currently falling block, which is stored in curBlock.
I use a function called createRandomBlock() to create a block and put it in curBlock:
var blockTypeArr = [LBlock, SquareBlock, StraightBlock, SquigBlock];
var createRandomBlock = function(){
var block = blockTypeArr[Math.floor(Math.random()*blockTypeArr.length)];
var randomBlock = new block();
return randomBlock;
};
curBlock = createRandomBlock();
Once it's done falling I put it in the array and create a new block:
blockArr[blockArr.length] = curBlock;
curBlock = createRandomBlock();
If the newly created block hasn't yet been on screen then there's no problem. However, using the moveTo and translate methods of the new instance affect all instances of that class (I added an id property to make sure they were in fact distinct instances).
For example, using the JavaScript console,
>curBlock
SquigBlock
>blockArr
[SquareBlock, SquigBlock, SquigBlock]
As you can see, 3 SquigBlocks have fallen so far (2 in blockArr, 1 presently falling). Yet the only one I see is the one currently falling (curBlock), and checking the parameters, curBlock.getY(), blockArr[1].getY() and blockArr[2].getY() all return the same value. In other words, they're all being drawn in the same location.
How can I change it so that old blocks, no matter what the class, stay at the bottom of the screen, while the newly created block falls from the top without causing all other blocks of that class to move with it?
Thank you!
StraightBlock.prototype = new BlockTemplate(20, 100, "#00FFE5");
Well, that is only one BlockTemplate that is shared amongst with StraightBlock instances. You can see that new StraightBlock().moveTo == new StraightBlock().moveTo, ie two instances have the very same method which does affect the same x variable. Do not use new for creating the prototype, but Correct javascript inheritance:
function StraightBlock(){
BlockTemplate.call(this, 20, 100, "#00FFE5");
this.draw = function(){
ctx.fillStyle = this.getColor();
ctx.fillRect(this.getX(), this.getY(), 20, 100);
};
}
StraightBlock.prototype = Object.create(BlockTemplate.prototype);
StraightBlock.prototype = new BlockTemplate(20, 100, "#00FFE5");
Since this is called once, there is one var x that is closed over by the single getHeight that is shared among all instances of StraightBlock.
You should make two changes:
1 Use instance fields stored on this
function BlockTemplate(w, h, c){
this.height = h;
...
}
BlockTemplate.prototype.getHeight = function(){return this.height;};
...
2 Chain constructors
Have StraightBlock invoke its super-class constructor to add new versions of the methods to each instance created.
function StraightBlock(){
BlockTemplate.apply(this, arguments);
...
}
You could also just do constructor chaining, but that would mean that you are creating a new copy of each method for each instance. This can be expensive if you have a lot of short-lived instances of a "class".
The drawback of storing fields on this is that they can be unintentionally mutated by naive code. JavaScript does not have strong information hiding except via closed-over local variables, so if you want the robustness that you get via private fields in other languages, then your current design via local variables might be best.

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.

Categories