Why var a is undefined? Javascript OOP - javascript

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

Related

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

javascript function distance between two points

i have been learning javascript for a few days. and im having problems with the sintaxis and the semantics of my programs, i can make run this simple problem. i dont know whats wrong with it
//2. **Distance between two points**. Create a
//function that calculate the distance between two points
//(every point have two coordinates: x, y). _HINT: Your function
//Should receive four parameters_.
function Point(x,y,x1,y1){
this.x = x;
this.y = y;
this.x1 = x1;
this.y1 = y1;
this.distanceTo = function (point)
{
var distance = Math.sqrt((Math.pow(this.x1-this.x,2))+(Math.pow(this.y1-this.y,2)))
return distance;
};
}
var newPoint = new Point (10,100);
var nextPoint = new Point (25,5);
console.log(newPoint.distanceTo(nextPoint));
Try This instead:
function Point(x,y){
this.x = x;
this.y = y;
this.distanceTo = function (point)
{
var distance = Math.sqrt((Math.pow(point.x-this.x,2))+(Math.pow(point.y-this.y,2)))
return distance;
};
}
var newPoint = new Point (10,100);
var nextPoint = new Point (20,25);
console.log(newPoint.distanceTo(nextPoint))
In your distanceTo function you needed to refer to point.x and point.y instead as those are the points of nextPoint.
Hope this Helped :3
You're applying the hint in the wrong place. It's the distanceTo function that should take four parameters.
Given the hint, I wouldn't bother with the Point constructor (although I do like that thinking in general, it just doesn't seem to be what this question's looking for. Just go with distanceTo(x,y,x1,y1), and I don't think you'll have any trouble.
There's a few different ways to do this based on your code but since your function is expecting 4 inputs I went with that one.
function Point(x,y,x1,y1){
this.x = x;
this.y = y;
this.x1 = x1;
this.y1 = y1;
this.distanceTo = function() {
return Math.sqrt((Math.pow(this.x1-this.x,2))+(Math.pow(this.y1-this.y,2)))
};
}
var points = new Point (10,100,25,5);
console.log(points.distanceTo()
);
You also don't need to set the variable and then return it, you can just return the equation.
Your function function Point(x,y,x1,y1) gets four parameters, but you're declaring it with only two of them.
At the distanceTo function you should relate to point which's parameter of your invoked function.
It should go like this; point.x gives you 'X' value of passed object.
#Edit: My solution for this "problem" is;
var Point = function (x,y) {
this.x = x;
this.y = y;
this.distanceTo = function (point) {
let calculations = Math.sqrt((Math.pow(point.x-this.x,2))+(Math.pow(point.y-this.y,2)));
return calculations;
}
}
var firstPoint = new Point(0,0);
var secPoint = new Point(2,2);
console.log(firstPoint.distanceTo(secPoint));
Point constructor should have just two arguments x and y. And distanceTo should use the x and y of this point ant the other point (the one passed as parametter).
function Point(x, y){ // only x and y
this.x = x;
this.y = y;
this.distanceTo = function (point)
{
var dx = this.x - point.x; // delta x
var dy = this.y - point.y; // delta y
var dist = Math.sqrt(dx * dx + dy * dy); // distance
return dist;
};
}
var newPoint = new Point (10,100);
var nextPoint = new Point (25,5);
console.log(newPoint.distanceTo(nextPoint));
Note: Since all Point instances have the exact same distanceTo function, it is better to define it on the prototype instead of redefining it for each instance which will only increase creation time and waste a lot of ressources.
This is better:
function Point(x, y){ // only x and y
this.x = x;
this.y = y;
}
Point.prototype.distanceTo = function (point)
{
var dx = this.x - point.x; // delta x
var dy = this.y - point.y; // delta y
var dist = Math.sqrt(dx * dx + dy * dy); // distance
return dist;
};
var newPoint = new Point (10,100);
var nextPoint = new Point (25,5);
console.log(newPoint.distanceTo(nextPoint));
More about prototpes here!

this keyword inside anonymous function/constructor

To some extent I know whats happening in the code,just to clear my doubts I have posted this question
JavaScript
Point = function (x, y) //Here anonymous constructor is define
{
this.x = x;
this.y = y;
}
var points=[]
points.push(new Point(centerX + radius * Math.sin(angle),centerY - radius * Math.cos(angle))); //object is created and push in the array
And to access the value of points array,I can write points[i].x?
Yes, check this
var Point = function (x, y) //Here anonymous constructor is define
{
this.x = x;
this.y = y;
}
var points = [];
points.push(new Point(2,5));
points.push(new Point(3,11));
points.push(new Point(9,1));
for(var i = 0; i <points.length; i++){
console.log(points[i].x);
console.log(points[i].y);
};
Correct, you can access the object using its index i, and then you are dereferencing the object to access it's attribute/member
var Point = function (x, y)
{
this.x = x;
this.y = y;
}
var points = [];
points.push(new Point(1, 2));
var point = points[0];
alert(point.x == point[0].x);

Function in other function is not accessible

I declare two functions:
var vec = function(x,y){
this.x = x;
this.y = y;
};
var ray = function(start,end){
this.origin = start;
this.direction = end;
};
In the canvas.onmousemove event I would like to use these functions as objects:
canvas.onmousemove = function(event){
var ray = new ray(new vec(center_x,center_y), new vec(2,10));
};
But my browser is telling me that the functions are undefined
This is happening because the variable name (ray) is the same as the function name (ray)
Change ray variable name on this line
var ray = new ray(new vec(center_x,center_y), new vec(2,10));
Into a different name, like rayInstance. A meaningful name will help you on the future.
var rayInstance = new ray(new vec(center_x, center_y), new vec(2, 10));
var vec = function(x,y){
this.x = x;
this.y = y;
};
var ray = function(start,end){
this.origin = start;
this.direction = end;
};
var center_x =0, center_y=0;
(function() {
var rayInstance = new ray(new vec(center_x, center_y), new vec(2, 10));
alert(rayInstance.direction.x + " " + rayInstance.direction.y);
})();

javascript base object to create 2 other objects with different methods

I've been playing around with javascript for years, but I'm trying to get serious now. Studying, and into Objects.
I want to create a base object, and use it to create 2 other objects that are slightly different.
I thought this would work :
function movingObject(x, y, z){
this.x = x;
this.y = y;
this.z = z;
}
var positiveMover = new movingObject(x, y, z);
positiveMover.prototype.move = function(a, b){
yadda yadda
}
var negativeMover = new movingObject(x, y, z);
negativeMover.prototype.move = function(b, a){
adday adday
}
var pic = postiveMover(1, 2, 3);
pic.move(20, 10);
I get a undefined error on the move.....pretty sure I've got the wrong idea. Any advice would be appreciated - links to information, or the right keywords to google
I think it is more like two classes, that you want to build :
function movingObject(x, y, z){
this.x = x; this.y = y; this.z = z;
}
// positive mover : child class of movingObject
function positiveMover (x, y, z) {
// use parent class's constructor.
movingObject.apply(this,arguments);
};
// inherit parent's class.
positiveMover.prototype = Object.create(movingObject.prototype);
positiveMover.prototype.move = function(a, b){ yadda yadda }
However, if you seek a per-instance choice of a method, you could do :
function movingObject(x, y, z, movingMethod){
this.x = x; this.y = y; this.z = z;
this.move = movingMethod;
}
Or just set the move property of a moving object, thus overriding the default prototype :
function movingObject(x, y, z){
this.x = x; this.y = y; this.z = z;
}
movingObject.prototype.move= function(a,b) { /*some default code*/}
var oneMover = new movingObject(0,0,0);
oneMover.move = function(a,b) { /* some specific code */ };

Categories

Resources