Function in other function is not accessible - javascript

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

Related

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!

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

Issues with drawing reading values in javascript array - drawing in HTML5 canvas

I'm relatively new to all this and am trying to draw a basic shape on the html5-canvas. I think an option is to use 3.js for this but I was wondering if it's possible to do it without? The x,y values for each point are in arrays... Please help! Code and fiddle link below:
http://jsfiddle.net/mewchew/wJwL8/8/
var canvas = document.getElementById("myCanvas");
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
var width = canvas.width
var height = canvas.height
var xProp = 0.28
var yProp = 0.43
//Find canvas centerpoint - may need to change to global variable?
function centerPoint(width, height) {
x = Number(width) / 2;
y = Number(height) / 2;
return [x, y];
}
//Define diamond points
xy = centerPoint(width,height);
var pTx = newArray();
pTx[0] = x;
pTy[1] = x + xProp*x;
pTy[2] = x;
pTy[3] = x - xProp*x;
pTy[4] = x;
var pTy = newArray();
pTy[0] = y;
pTy[1] = y;
pTy[2] = y - yProp*y;
pTy[3] = y;
pTy[4] = y + yProp*y;
alert(String(pTx[1])+String(pTy[1]));
//Draw diamond
ctx.beginPath();
ctx.moveTo(pTx[0], pTy[0]);
ctx.lineTo(pTx[1],pTy[1]);
ctx.lineTo(pTx[2],pTy[2]);
ctx.lineTo(pTx[3],pTy[3]);
ctx.lineTo(pTx[4],pTy[4]);
ctx.closePath();
ctx.fillstyle() = "#FFFFFF"
ctx.fill();
} else {
// canvas-unsupported code here
log('Fail');
}
You had couple of errors in your script
First:
newArray() should be new Array()
new Array()
^-------- see space
Second:
var pTx = newArray();
pTx[0] = x; // ---> ptx ok
pTy[1] = x + xProp*x; // ---> its pty? why? change all to ptx
pTy[2] = x; // ---> change to ptx
pTy[3] = x - xProp*x; // ---> change to ptx
pTy[4] = x; // ---> change to ptx
It should be
var pTx = new Array();
pTx[0] = x;
pTx[1] = x + xProp*x;
pTx[2] = x;
pTx[3] = x - xProp*x;
pTx[4] = x;
Third
fillStyle is not a method its a property
ctx.fillstyle() = "#FFFFFF"
It should be
ctx.fillstyle = "#FFFFFF"
Demo

mouse speed javascript function

Working on some javascript. I found a pretty good function that calculates the speed of the cursor. The problem is that i want to return the actual value, not a callback. How would you do that?
function makeVelocityCalculator(e_init, callback) {
var x = e_init.clientX,
y = e_init.clientY,
t = Date.now();
return function(e) {
var new_x = e.clientX,
new_y = e.clientY,
new_t = Date.now();
var x_dist = new_x - x,
y_dist = new_y - y,
interval = new_t - t;
// update values:
x = new_x;
y = new_y;
t = new_t;
var velocity = Math.sqrt(x_dist*x_dist+y_dist*y_dist)/interval;
callback(velocity);
};
}
well , then change that function to return velocity, instead of "callback(velocity)"
Js Fiddle sample
Or you can use it the way it was intended
makeVelocityCalculator(initialEvent, function(velocity) {
console.log("velocity is", velocity);
});
is pretty much same as
var velocity = makeVelocityCalculator(initialEvent);
console.log("velocity is", velocity);
function calculateVelocity(e_init) {
var x = e_init.clientX,
y = e_init.clientY,
t = Date.now();
return function(e) {
var new_x = e.clientX,
new_y = e.clientY,
new_t = Date.now();
var x_dist = new_x - x,
y_dist = new_y - y,
interval = new_t - t;
// update values:
x = new_x;
y = new_y;
t = new_t;
var velocity = Math.sqrt(x_dist*x_dist+y_dist*y_dist)/interval;
return velocity;
};
}
var velocity = calculateVelocity(e_init)(e);
// OR
var v_f = calculateVelocity(e_init);
// then some code ...
v_f(e);
Use an immediately invoking function (function(){})() if you want the call to calculateVelocity to return the velocity, otherwise return the function, which in turn returns the velocity.

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