Few Instance of object Javascript - javascript

I want to create a few instance of this class
var fruit = {
texture: new Image(),
speed: 5,
x: 0,
y: 0,
};
function fruits(speed, x, y)
{
fruit.speed = speed;
fruit.x = x;
fruit.y = y;
return fruit;
};
but when i create new object the all value was overridet by last created object. How can i repair this?
My loop:
var apples = [];
for(var i = 0; i < 10; i++)
{
apples[i] = new fruits(5, Math.floor((Math.random()*775)+1), 0);
apples[i].texture.src = "_img/apple.png";
}

The other answers which are appearing here are just bizarre. Here's the solution:
function fruits(speed, x, y)
{
this.texture = new Image( );
this.speed = speed;
this.x = x;
this.y = y;
};
Notice that the keyword this is used to set attributes. That means that when you call
var apple = new fruits( blah blah );
then apple will be set to a new object which has texture, speed, x and y attributes. There is no need to reference some global object to store these; they are stored in the newly created object itself.
Also I would rename it; the convention is to use singular names and a capital first letter for objects, so Fruit would make more sense (allowing new Fruit(...))

function Fruit( speed, x, y ){
var fruit = {}; // or use some base object instead of {}
fruit.texture = new Image();
fruit.speed = speed || 5;
fruit.x = x || 0;
fruit.y = y || 0;
return fruit;
};
var apples = [];
for( var i=0; i<10; i++ ){
apples[i] = Fruit( 5, Math.floor((Math.random()*775)+1), 0 );
apples[i].texture.src = "_img/apple.png";
}
Douglas Crockford - Power Constructor, 'new', 'this' and more

You got an object here:
var fruit = {
texture: new Image(),
speed: 5,
x: 0,
y: 0, // Note the superflous comma, which might break the code in some IE versions
};
And a function here:
function fruits(speed, x, y) {
fruit.speed = speed;
fruit.x = x;
fruit.y = y;
return fruit;
};
The function modifies above object whenever it is called and returns it.
Now, what you want is a constructor, but you don't have one here.
This, would be a constructor for a new Fruit:
function Fruit(speed, x, y) {
this.texture = new Image();
this.speed = speed || 5; // Note: Using logical OR to emulate default values for the argument
this.x = x || 0;
this.y = y || 0;
// Note: There is no return here!
}
var a = new Fruit(2, 1, 10);
var b = new Fruit(4, 10, 20);
a === b; // Returns false, you got two instances :)
new may have the functionality of being able to create instances of a Function, but you can still override this behavior by returning manually from within the constructor Function.
Also, even if you left out the return fruit in your original code, you would get back an empty instance of fruits since you don't assign any properties to the newly created instance.
In my Fruit example I reference the instance object via the this keyword, so I can assign speed, image, x and y to each instance created.
You might also want to read:
http://bonsaiden.github.io/JavaScript-Garden/#function.constructors
http://bonsaiden.github.io/JavaScript-Garden/#function.this

function fruits(speed, x, y) {
return {
texture: new Image(),
speed: speed,
x: x,
y: x,
}
};

Try such constructor:
function Fruit(speed, x, y) {
return {
speed: speed,
x: x,
y: y
}
}
alert(new Fruit("mySpeed", 1, 2).speed);

Related

JavaScript create objects in for-loop

I'm making a canvas game in JavaScript and have some trouble saving the data. I'm placing images on the canvas with a for-loop and I want to save information for each image in objects. For each image an object.
function CreateBlocks(){
for(var i = 0; i <= blocks; i++){
var img = new Image();
img.src = "/images/Block.png";
blockObject = {
x: x,
y: y,
points: 10
}
ctx.drawImage(img,x,y);
x += 100;
y += 100;
}
}
Now this obviously overwrites the blockObject everytime it loops. I tried adding to loop value to the name of the object like block[i]Object or blockObject[i] but that returns syntax errors.
I could just create a single dimension array for each value, but that seems rather messy to me. How can I create the objects in the loop?
Simply use an array and push the new object each time:
function CreateBlocks(){
var arr = [];
for(var i = 0; i <= blocks; i++){
var img = new Image();
img.src = "/images/Block.png";
arr.push({
x: x,
y: y,
points: 10
});
ctx.drawImage(img,x,y);
x += 100;
y += 100;
}
}
If you create a blockObjects array, your second idea, using the blockObject[i] syntax will work:
var blockObjects=[];
function CreateBlocks(){
for(var i = 0; i <= blocks; i++){
var img = new Image();
img.src = "/images/Block.png";
blockObjects[i] = {
x: x,
y: y,
points: 10
};
ctx.drawImage(img,x,y);
x += 100;
y += 100;
}
}

Create instance without `new` operator with variable argument list

I want to create an instance of a Point with and without the new operator like:
Point(5, 10); // returns { x: 5, y: 10 }
// or
new Point(5, 10); // also returns { x: 5, y: 10 }
I got it working so far with the help of StackOverflow.
function Point() {
if (!(this instanceof Point)) {
var args = Array.prototype.slice.call(arguments);
// bring in the context, needed for apply
args.unshift(null);
return new (Point.bind.apply(Point, args));
}
// determine X and Y values
var pos = XY(Array.prototype.slice.call(arguments));
this.x = pos.x;
this.y = pos.y;
}
But that looks horrible, I am even unshifting null into the array so I can use apply. That just doesn't feel right.
I found a lot of solutions how to achieve it with new constructors and constructor wrappers but I want to keep it as simple as possible (it's just a plain, simple Point).
Is there an easier way to achieve this behaviour?
If you don't mind using ECMAScript 5 functions, Object.create() could help:
function Point()
{ var args = Array.prototype.slice.call(arguments);
if (this instanceof Point) return Point.apply(null, args);
var pos = XY(args);
var result = Object.create(Point.prototype);
result.x = pos.x;
result.y = pos.y;
return result;
}
If you need ECMAScript 3 compatibility, this crazy, convoluted solution is yet another one (note that it's just a wrapper for an internal equivalent of new Point):
function Point()
{ var pos = XY(Array.prototype.slice.call(arguments));
function internalPoint()
{ this.x = pos.x;
this.y = pos.y;
}
internalPoint.prototype = Point.prototype;
return new internalPoint;
}

javascript setting attribute of prototype to attribute of object

To begin with, I don't fully understand the prototypal structure of Javascript so this may not be possible.
If I have ...
var vector = function( x, y ) {
this.x = x || 0;
this.y = y || 0;
}
var obj = function() {
this.position = new vector( 0, 0, 0 );
}
var cube = new obj();
... how can I add a property x to obj such that calling cube.x is equivalent to cube.position.x. I think it should be possible to make properties of each reference the same value, but I'm just not sure of the syntax. Something like obj.prototype.x = obj.position.x doesn't work because obj.position is undefined.
I would like the following behaviour to be possible
alert(cube.position.x); // 0
alert(cube.x); // 0
cube.position.x = 2;
alert(cube.position.x); // 2
alert(cube.x); // 2
cube.x = 4;
alert(cube.position.x); // 4
alert(cube.x); // 4
Is this possible?
I should probably mention that I'm working with Three.js so rewriting the objects isn't an option, just adding to them and their prototypes.
To get cube.x to return whatever cube.position.x contains, you'd need to define accessors and mutators for obj.prototype.x. Accessors and mutators are a relatively newer feature in JavaScript, and are not supported in most versions of IE.
var vector = function( x, y ) {
this.x = x || 0;
this.y = y || 0;
}
var obj = function() {
this.position = new vector( 0, 0, 0 );
}
obj.prototype = {
...your prorotype methods here...
};
Object.defineProperty(obj.prototype, 'x', {
get: function () {
return this.position.x;
},
set: function (val) {
this.position.x = val;
}
});
//alternatively:
obj.prototype = {
get x() {
return this.position.x;
},
set x(val) {
this.position.x = val;
}
};
var cube = new obj();
cube.x; //0
cube.x = 10;
cube.position.x; //10

Create new Instance of function referenced by a variable

I'm trying to create a way to store and load maps for an HTML5 canvas game. In order to do so, I must create new instances of objects (functions) referenced by a variable. This is my code.
function Map(w, h) {
if (typeof w == "undefined")
this.width = 640;
else
this.width = w;
if (typeof h == "undefined")
this.height = 480;
else
this.height = h;
this.obj = new Array();
this.x = new Array();
this.y = new Array();
this.backgroundColor = "#C0C0C0";
}
Map.prototype.addObject = function(cl, xx, yy) {
this.obj.push(cl);
this.x.push(xx);
this.y.push(yy);
}
function newInstance(o, x, y) {
this.tmp = new o(); //This is what doesn't work.
tmp.x = x;
tmp.y = y;
objects.push(tmp);
tmp.create();
}
Map.prototype.load = function() {
for (var i = 0; i < this.obj.length; i++) {
newInstance(this.obj[i], this.x[i], this.y[i]);
}
}
I want it to be used as such:
//When I create the map.
var mMain = new Map();
//This cannot be new Player() and new Block() because I don't want to load the map yet. I'm just creating the map.
mMain.addObject(Player, 320, 240);
mMain.addObject(Block, 0, 256);
mMain.addObject(Block, 32, 256);
//etc...
//When I load the map.
mMain.load();
Just an example of how the Player and Block objects work.
function Player() {
this.x = 0;
this.y = 0;
//Other variables irrelevant to this problem.
}
//Block object code
I figured out the problem. I had forgotten to check all of my code before posting, so I gave false information. Instead of "function Player()", I had "var Player = ObjectResource;" because I wanted it to extend the ObjectResource function. I just had to change it to what I had posted.

How to create separate objects using Modular JavaScript pattern

I'm trying to update the interval value x but not succeeding. I hope to eventually have different pawn objects with internal values I can update when keypress up/down/left/right to redraw the canvas.
Code Update: Able to update x, y values now, but not sure about creating seperate objects using modular JavaScript pattern.
JavaScript using jQuery 1.5.1:
//Constructors
var pawn = (function() {
var x = 25;
var y = 25;
var getX = function() {
return x;
};
var getY = function() {
return y;
};
function _drawPawn(x,y) {
var x = x || 25;
var y = y || 25;
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var b = $('body');
var winH = b.height();
var winW = b.width();
$(canvas).attr('height',winH).attr('width',winW);
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.lineWidth="3";
ctx.arc(x, y, 10, 0, Math.PI * 2, true); // circle
ctx.stroke();
}
}
function left() {
x = 100;
y = 100;
}
return {
getX:getX,
getY:getY,
draw: function drawPawn(x,y) {
_drawPawn(x,y);
},
left:left
}
})();
//Init
$(function() {
var b = pawn;
b.left();
alert(b.getX());
var a = pawn;
alert(a.getX());
//b.draw();
});
and the html:
<canvas id="canvas" height="800px" width="600px">
Download a modern browser like Internet Explorer 9, Firefox, Safari or Chome to view this.
</canvas>
As it is currently written, your getX() function will be automatically invoked with the supplied (empty) parameter list, and return x, which is then equivalent to:
var getX = x;
which will give getX the value of x at the time it was declared.
To fix, removed the parentheses:
var getX = function() {
return x;
};
You also need to fix this function in your returned object:
draw: function drawPawn(x, y) {
_drawPawn(x, y);
}
Since the apparent intent is to call draw without parameters and use the currently bound x and y values, it should be:
draw: function drawPawn() {
_drawPawn(x, y);
}
First like alnitak said remove paranthese from getX, getY.
If u want different pawn objects you should use var b = new pawn()

Categories