Why is object property changed for all instances? - javascript

I wanted to encapsulate the position of a sprite within another object. So that instead of using tile.x and tile.y I would access via tile.position.x and tile.position.y.
Yet once I set the value of tile.position within the init-method all the instances of the tile-object change to the same value. Why is that?
As when I set tile.x everything works as expected, meaning each object gets the right value.
This is how I create the multiple instances:
In a for loop I am creating multiple instances of said object:
for (var y = 0; y < 10; ++y) {
for (var x = 0; x < 10; ++x) {
var tile = Object.create(tileProperty);
tile.init(x, y);
...
}
}
And this is the cloned object:
var tileProperty = {
// this works
x: null,
y: null,
// this will get changed for ALL instances
position: {
x: null,
y: null
},
init: function(x, y) {
this.name = x.toString() + y.toString();
this.x = x;
this.y = y;
this.position.x = x;
this.position.y = y;
this.canvas = document.createElement('canvas');
var that = this;
$(this.canvas).bind('click', function() {
console.log(that.position, that.x, that.y);
});
document.body.appendChild(this.canvas);
}
}

Use this:
var tileProperty = {
position: { // we will inherit from this
x: null,
y: null,
init: function(x, y) {
this.x = x;
this.y = y;
}
},
init: function(x, y) {
this.name = x.toString() + y.toString();
// create an own Position object for each instance
this.position = Object.create(this.position);
// and initialize it
this.position.init(x, y); // you might inline this invocation of course
…
},
…
}

You're having a reference to the same position object in all your objects.
What you should do is using the standard prototype solution :
function tileProperty() {
this.position = {
x: null,
y: null
};
}
tileProperty.prototype.init = function(x, y) {
this.name = x.toString() + y.toString();
this.x = x;
this.y = y;
this.position.x = x;
this.position.y = y;
this.canvas = document.createElement('canvas');
var that = this;
$(this.canvas).bind('click', function() {
console.log(that.position, that.x, that.y);
});
document.body.appendChild(this.canvas);
}
and then build your instance using
var tp = new tileProperty();

Related

JavaScript - - Class Design pattern to Delegation Design pattern, new Constructor to Object.create()

I am trying to convert JavaScript Class Design Pattern to Delegation Design Pattern. (You Don't Know JS Series by Kyle Simpson)
I am not able to change the new Constructor to Object.create() in [Symbol.iterator] function of Matrix object of my Delegation Design code. I am not able setup a proper iterator for for of loop.
I am working with the Matrix Iterator code in Eloquent JavaScript book, Section: Iterable Interface Section. You can find the proper code in the link.
Nevertheless, I have Included the same code below.
Class Design Pattern Code as in the Link:
class Matrix {
constructor(width, height, element = (x, y) => undefined) {
this.width = width;
this.height = height;
this.content = [];
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
this.content[y * width + x] = element(x, y);
}
}
}
get(x, y) {
return this.content[y * this.width + x];
}
set(x, y, value) {
this.content[y * this.width + x] = value;
}
}
class MatrixIterator {
constructor(matrix) {
this.x = 0;
this.y = 0;
this.matrix = matrix;
}
next() {
if (this.y == this.matrix.height) return {done: true};
let value = {
x: this.x,
y: this.y,
value: this.matrix.get(this.x, this.y)
};
this.x++;
if (this.x == this.matrix.width) {
this.x = 0;
this.y++;
}
return {value, done: false};
}
}
Matrix.prototype[Symbol.iterator] = function() {
return new MatrixIterator(this);
};
let matrix = new Matrix(2, 2, (x, y) => `value ${x},${y}`);
for (let {x, y, value} of matrix) {
console.log(x, y, value);
}
Delegation Pattern Code that I am trying to create:
var Matrix = {
init: function(width, height, element = (x, y) => undefined) {
this.width = width;
this.height = height;
this.content = [];
for(let y = 0; y < height; y++) {
for(let x = 0; x < width; x++) {
this.content[y * width + x] = element(x, y);
}
}
},
[Symbol.iterator]: function() {
var matrixIt = Object.create(MatrixIterator);
????????? // **I have no clue what to do here, or even if I am right upto this point**
},
get: function(x, y) {
return this.content[y * this.width + x];
},
set: function(x, y, value) {
this.content[y * this.width + x] = value;
},
}
var MatrixIterator = Object.create(Matrix);
MatrixIterator = {
setup: function(matrix) {
this.x = 0;
this.y = 0;
this.matrix = matrix;
},
next: function() {
if (this.y == this.matrix.height) return {done: true};
let value = {
x: this.x,
y: this.y,
value: this.matrix.get(this.x, this.y)
};
this.x++;
if (this.x == this.matrix.width) {
this.x = 0;
this.y++;
}
return {value, done: false};
}
}
let matrix = Object.create(Matrix);
matrix.init(2, 2, (x, y) => `value ${x},${y}`);
for (let {x, y, value} of matrix) {
console.log(x, y, value);
}
Any clue to where I maybe going wrong is appreciated.
After inspecting my Delegation Pattern code in the question I gained more clarity on concepts of Delegation Pattern flow. Refer You Don't Know JS
The solution:
var Matrix = {
init: function(width, height, element = (x, y) => undefined) {
this.width = width;
this.height = height;
this.content = [];
for(let y = 0; y < height; y++) {
for(let x = 0; x < width; x++) {
this.content[y * width + x] = element(x, y);
}
}
},
get: function(x, y) {
return this.content[y * this.width + x];
},
set: function(x, y, value) {
this.content[y * this.width + x] = value;
}
}
var MatrixIterator = {
setup: function(matrix) {
this.x = 0;
this.y = 0;
this.matrix = matrix;
},
[Symbol.iterator]: function() {
return this;
},
next: function() {
if (this.y == this.matrix.height) return {done: true};
let value = {
x: this.x,
y: this.y,
value: this.matrix.get(this.x, this.y)
};
this.x++;
if (this.x == this.matrix.width) {
this.x = 0;
this.y++;
}
return {value, done: false};
}
}
Object.setPrototypeOf(MatrixIterator, Matrix);
let matrix = Object.create(Matrix);
matrix.init(2, 2, (x, y) => `value ${x},${y}`);
let matrixIter = Object.create(MatrixIterator);
matrixIter.setup(matrix);
for (let {x, y, value} of matrixIter) {
console.log(x, y, value);
}
The solution provided here can be improved further.

How to add object variable to an array using "new"?

I've got this object variable:
var Background = {
x: 0,
y: 0,
speed: 4,
initialize: function (x, y){
this.x = x;
this.y = y;
move: function(){
this.x -= this.speed;
}
};
And I'd like to create new object variable and add it to an array:
background_container = []
background_container.push(new Background())
But it throws an error:
"Uncaught TypeError: Background is not a constructor"
Although it works with normal:
function name() {}
var test_var = new name()
So my guess is that "new" works only for functions. But how can I do it with variable objects like the one before? (I want to have multiple of them in one array and not just multiple references to one object)
With ES5 and below you can create a function which acts as a constructor. Use this inside to bind properties to the current object which is returned from the new operator. Also you can leave the initalize function (if you intend to use this only one time) and pass parameters into the function or constructor directly.
function Background(x, y) {
this.x = x || 0;
this.y = y || 0;
this.speed = 4;
this.move = function() {
this.x -= this.speed;
}
};
var backgrounds = [];
backgrounds.push(new Background(1, 3));
console.log(backgrounds[0].x);
console.log(backgrounds[0].y);
With ES6 and higher you can use Ecmascript's new syntax for creating classes.
class Background {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
this.speed = 4;
}
move() {
this.x -= this.speed;
}
};
const backgrounds = [];
backgrounds.push(new Background(1,3));
console.log(backgrounds[0].x);
console.log(backgrounds[0].y);

How to extend a class inside a namespace in javascript?

var sl = sl || {}
sl.Shape = function(){
this.x = 0;
this.y = 0;
};
sl.Shape.prototype.move = function(x,y){
this.x += x;
this.y += y;
};
sl.Rectangle = function(){
sl.Shape.call(this);
this.z = 0;
};
The next line produces the error (Object prototype undefined, has to be Object or null). As far as I can see this is because Shape is "namespaced".
sl.Rectangle.protoype = Object.create(sl.Shape.protoype);
sl.Rectangle.protoype.constructor = sl.Rectangle;
How do I do this correctly?
You should use word prototype instead protoype.
You have misspelled the word "prototype" as Andrii pointed out, try this example:
(function() {
var sl = sl || {};
function Shape() {
this.x = 0;
this.y = 0;
}
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
};
function Rectangle() {
Shape.apply(this, arguments);
this.z = 0;
};
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
sl.Shape = Shape;
sl.Rectangle = Rectangle;
// expose
window.sl = sl;
}());
Usage
var shape = new sl.Shape();
var rect = new sl.Rectangle();

JS object inheritance with attributes

Im trying to get a very simple inheritance pattern for my Project going, extending from a base class into a specialized class. However, my specialized class's attributes are being overwritten by the parent's attributes.
Why is that and how can i fix it ?
thanks,
function Ship(className, x, y){
this.className = className;
this.x = x;
this.y = y;
this.speed = 0;
}
function Corvette(className, x, y){
this.className = className;
this.x = x;
this.y = y;
this.speed = 100;
Ship.call(this, className, x, y)
}
Corvette.prototype = Object.create(Ship.prototype);
var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);
console.log(Corvette.className) // "Smallish" - correct via parameter.
console.log(Corvette.speed) // should be 100, is 0 - not correct, "static" from parent attribute
console.log(Corvette.constructor.name) // Ship
Why you have the same properties in the child object which are already in the parent's?
I suggest you to do
function Ship(className, x, y, speed = 0) {
this.className = className;
this.x = x;
this.y = y;
this.speed = speed;
}
function Corvette(className, x, y, speed = 100) {
Ship.call(this, className, x, y, speed);
}
Corvette.prototype = Object.create(Ship.prototype);
Corvette.prototype.constructor = Corvette;
var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);
console.log(corvette.className) // "Smallish" - correct via parameter.
console.log(corvette.speed) // should be 100, is 0 - not correct, "static" from parent attribute
console.log(corvette.constructor.name) // Ship
and if your browser supports some features of ES6 use this feature ES6 classes.
class Ship { // And also Ship is an abstractionm so you can use `abstract` keyword with it
constructor(className, x, y, speed = 0) {
this.className = className;
this.x = x;
this.y = y;
this.speed = speed;
}
}
class Corvette extends Ship {
constructor(className, x, y, speed = 100) {
super(className, x, y, speed);
}
}
var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);
console.log(corvette.className) // "Smallish" - correct via parameter.
console.log(corvette.speed) // should be 100, is 0 - not correct, "static" from parent attribute
console.log(corvette.constructor.name) // Ship
You only need to move Ship.call(this, className, x, y) at the start of Corvette function.
Also, next time, before posting code, check it is correct, you wrote console.log(Corvette) instead of console.log(corvette)
Another thing: you do not need to repeat params you do not want to overwrite
function Ship(className, x, y){
this.className = className;
this.x = x;
this.y = y;
this.speed = 0;
}
function Corvette(className, x, y){
Ship.call(this, className, x, y)
this.speed = 100;
}
Corvette.prototype = Object.create(Ship.prototype);
var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);
console.log(corvette.className)
console.log(corvette.speed)
console.log(corvette.constructor.name)
You should invoke the parentclass contructor first and then override the properties, this way the properties set by Corvette will not be changed by the parent class i.e.:
function Corvette(className, x, y){
Ship.call(this, className, x, y)
this.speed = 100;
}

Why var a is undefined? Javascript OOP

I have this code. It creates an object with x and y field. I want to add a method, which creates new object with additional width and height fields. But despite my tryings it keeps returning undefined. What is wrong?
JSFiddle
function $ (x, y) {
this.x = x;
this.y = y;
return this;
}
$.prototype.$ = function (x, y) {
this.width = x - this.x;
this.height = y - this.y;
return this;
}
var a = $(10,10).$(30,30);
alert(a.width);
var a = (new $(10,10)).$(30,30); //You need new
alert(a.width);
Also it might not be a good idea to have an instance function of a class to have the same name as the class -- it is a little confusing.
Here is how you can do what you want to do with 2 "Point" objects (as asked for in the comments):
var Point = (function(){
var Point = function(x, y) {
this.width = x;
this.height = y;
}
Point.prototype.removePoint = function(point) {
return new Point(point.width - this.width, point.height - this.height);
}
return Point;
})()
var a = new Point(10,10);
var b = new Point(30,30);
var c = a.removePoint(b);
alert(c.width);
Fiddle: http://jsfiddle.net/maniator/d3fx7/
You missed the new before $; This works:
var a = new $(10,10).$(30,30);

Categories

Resources