How do i call a function on another function - javascript

I am trying to call a function does multiplication On another function that accepts two numbers as parameters. i Have tried using constructor and nested function, but to no avail. i have tried the followings:
function Coordinate(a, b) {
var x, y;
return {x: a, y: b};
function multiply(n) {
x * n;
y * n;
}
}
var makeCoordinate = new Coordinate(2,3);
console.log(makeCoordinate.multiple(2));
// expected output: 4 6;

You should set multiply to be on the Coordinate's prototype so that when you call new Coordinate, the instantiated object will have multiply as a method. For it to work, you should also set this.x and this.y instead of returning an object directly:
function Coordinate(a, b) {
this.x = a;
this.y = b;
}
Coordinate.prototype.multiply = function(n) {
this.x *= n;
this.y *= n;
return this;
}
var makeCoordinate = new Coordinate(2,3);
console.log(makeCoordinate.multiply(2));
Or, if you wanted multiply to return just the multiplied coordinates without changing the original object, then return the coordinates alone:
function Coordinate(a, b) {
this.x = a;
this.y = b;
}
Coordinate.prototype.multiply = function(n) {
return [this.x * n, this.y * n];
}
var makeCoordinate = new Coordinate(2,3);
console.log(makeCoordinate.multiply(2));

The answer modified two parts:
the creation of Coordinate members
multiple -> multiply
Hope this help :)
function Coordinate(a, b) {
this.x = a;
this.y = b;
this.multiply = function(n) {
return this.x * n + " " + this.y * n;
}
}
var makeCoordinate = new Coordinate(2,3);
console.log(makeCoordinate.multiply(2));

Well, firstly your console.log is calling multiple, not multiply.
Second, try an approach like this:
function Coordinate( a, b )
{
function multiply( n )
{
this.x = this.x * n;
this.y = this.y * n;
return this;
}
var co = { x: a, y : b };
co.multiply = multiply.bind( co );
return co;
}

Having clarified in the comments, the (simplest)solution is:
// important code
function Coordinate(a,b) {
this.x = a;
this.y = b;
this.multiply = function (n) {
this.x = this.x*n;
this.y = this.y*n;
}
}
// test code
let coord = new Coordinate(2,3);
console.log("Original Coordinate:");
console.log(coord);
coord.multiply(2);
console.log("Changed Coordinate: ");
console.log(coord);
You could also put the function in the prototype if you don't want a copy of it in every Coordinate object.

Related

Dynamic Class Properties in JavaScript

How do you make a class property that recalculates each time you use it?
class myClass {
constructor(x, y) {
this.x = x
this.y = y
this.percent = x/y * 100
}
}
var test = new myClass(5, 10)
test.percent
//50
test.x = 10
test.percent
//still 50
I want test.percent to change 100 and adapt to other changes.
Can I do this without turning the variable into a function?
What you are looking for is called a getter. A getter is recomputed everytime its property is accessed:
class myClass {
constructor(x, y) {
this.x = x
this.y = y
}
get percent(){
return this.x / this.y * 100
}
}
var test = new myClass(5, 10)
console.log(test.percent) //50
test.x = 10
console.log(test.percent) //100
There are two ways you can do this
You can have this.percent as a function
class myClass {
constructor(x, y) {
this.x = x;
this.y = y
this.percent = function() {
return this.x / this.y * 100
}
}
}
var test = new myClass(5, 10)
console.log(test.percent())
test.x = 10
console.log(test.percent())
You can also use getter
class myClass {
constructor(x, y) {
this.x = x;
this.y = y;
}
get percent() {
return this.x / this.y * 100
}
}
var test = new myClass(5, 10)
console.log(test.percent)
test.x = 10
console.log(test.percent)
You can use an accessor ( getter ) to alter the data each time you are accessing it.
In your case, you can replace the percent property by a getter.
class myClass {
constructor(x, y) {
this.x = x
this.y = y
}
get percent() {
return this.x / this.y * 100;
}
}
var test = new myClass(5, 10)
console.log(test.percent);
//50
test.x = 10
console.log(test.percent);
//now 100
I have also edited your code to use this to access x and y

best design practice to separate common code?

I have a card class:
function Card() {
this.image = new Image();
this.x = 0;
this.y = 400;
this.initialX = 0;
this.initialY = 0;
this.scaleFactor = 4;
this.setImage = function(ii){
this.image.src = ii;
};
this.getWidth = function(){
if (this.image == null){
return 0;
}
return this.image.width / this.scaleFactor;
}
this.getHeight = function(){
if (this.image == null){
return 0;
}
return this.image.height / this.scaleFactor;
}
this.pointIsInCard = function(mx, my){
if (mx >= this.x && mx <= (this.x + this.getWidth()) && my >= this.y && my <= (this.y + this.getHeight()))
{
return true;
}
else{
return false;
}
};
};
I then have a deck class:
function Deck(x, y, w, h){
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.cards = [];
}
I need to add a method in Deck class similar to pointIsInCard instead it will be called pointIsInDeck. The logic will be same i.e to check whether the passed in point falls in the boundary of the object. So seeing this duplication of code I wanted to know what is a good design practice to avoid this duplication? One option I thought of was to extract the method out and create a function for generic object with x, y, width, height but again from OOP principles I thought this method should belong to the class/object. I appreciate any help! Thanks!
A common approach for what you're doing is to attach a Rectangle or similar instance with that functionality to both of your objects, that is:
class Rectangle {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
containsPoint(x, y) {
return x >= this.x && x =< this.width &&
y >= this.y && y =< this.height;
}
}
Then just add it to Card and Deck:
function Card() {
this.rect = new Rectangle(/* Your card shape */);
// ...
}
function Deck() {
this.rect = new Rectangle(/* Your deck shape */);
// ...
}
And you can do:
card.rect.containsPoint();
deck.rect.containsPoint();
If these are classes related to drawing, they would both inherit from something like Rectangle, which they would both inherit this behaviour from.
If they are gameplay-related, I would prefer them each referencing a Rectangle (or its subclass) that they would delegate all UI-related tasks to; then reduce this to the previous paragraph's solution.
You can use Function.prototype.call() to set this at a function call
function Card() {
this.x = 1; this.y = 2;
};
function Deck() {
this.x = 10; this.y = 20;
}
function points(x, y) {
// do stuff
console.log(x, this.x, y, this.y); // `this`: `c` or `d`
}
var c = new Card();
var d = new Deck();
points.call(c, 3, 4); // `this`: `c` within `points` call
points.call(d, 100, 200); // `this`: `d` within `points` call

Constructer in Javascript does not return correct value that is passed by prototype function

I have written a code with constructer Vector(it has two parameters) and I wish to pass different set of parameters through a prototype function and want to sum up the values for both set of parameters.
But I am facing a issue with printing final Vector.
function Vector(x, y) {
this.x = x;
this.y = y;
console.log(x, y);//initially this prints (3,3)
return (x, y);
}
Vector.prototype.plus = function (a, b) {
this.x = this.x + a;
this.y = this.y + b;
console.log(this.x, this.y);// After passing (1,9) it prints (4,12)but
return (this.x, this.y); //after returning (this.x, this.y) it
//prints only Y coordinate as 12
}
var type_vector = new Vector(3, 3);
console.log(type_vector.plus(1, 9));
Output: (3,3),(4,12),12
I believe you're from a python background, for there (x, y) is returned as a tuple. In JS if you return (x, y); it will be the value at the closing parenthesis (y, in this case). You must use an object or an array for your objective.
try this on console:
var a = (3, 4, 5, 6);
console.log(a);
Well, in JavaScript if you want to return an array you can use the [] notation.
Diff. this with you version :
function Vector(x, y) {
this.x = x;
this.y = y;
console.log(x, y);
return this;
}
Vector.prototype.plus = function(a, b) {
this.x = this.x + a;
this.y = this.y + b;
console.log(this.x, this.y);
return [this.x, this.y];
};
var type_vector = new Vector(3, 3);
console.log(type_vector.plus(1, 9));

Constructor function that creates circle objects javascript

I want to make a constructor function that creates circle objects. I need to add two methods to it. I want first method (translate()) to takes two number parameters and adds the first one to the Circle's x-coordinate and adds the second one to the Circle's y-coordinate.
and I want the second method to take a Circle parameter and return yes if the two Circles intersect, but return false otherwise.
function Circle (xPoint, yPoint, radius) {
this.x = xPoint;
this.y = yPoint;
this.r = radius;
}
function translate(horiz, vert) {
return ((horiz + this.x) && (vert + this.y));
}
How would I implement the second, intersects(), method?
Here you go:
function Circle(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
this.translate = function(h, v) {
this.x += h;
this.y += v;
};
this.intersect = function(circle) {
var centerDistance = Math.pow(this.x - circle.x, 2) + Math.pow(this.y - circle.y, 2);
return Math.pow(this.r - circle.r, 2) <= centerDistance && centerDistance <= Math.pow(this.r + cirle.r, 2);
};
}

Javascript calling a class method using variables in the class

I'm incredibly new to javascript and the way classes and methods work are confusing me.
Basically I have code like this:
function container(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
this.sumUp = function addUp(x, y, z) {
var a = x + y + z;
};
}
What I want to do is elsewhere in my code use the function defined within the container, using the values in container. How do I actually go about doing this?
Something along the lines of
container1 = new container (1, 2, 3);
container.sumUp(this.x, this.y, this.z);
Or something like that. I'm very confused and thinking I'm going about the whole thing wrong.
I think you want somwthing like this:
function Container(x, y, z){
this.x = x;
this.y = y;
this.z = z;
this.sumUp = function addUp(x, y, z){
alert(this.x + this.y + this.z);
};
}
container_instance = new Container(1, 2, 3);
container_instance.sumUp();
But I recomend:
function Container(x, y, z){
this.x = x;
this.y = y;
this.z = z;
}
Container.prototype.sumUp = function addUp(x, y, z){
alert(this.x + this.y + this.z);
};
container_instance = new Container(1, 2, 3);
container_instance.sumUp();
That is how it works (short):
In JavaScript you have objects, they are like hashes:
var obj = {
'a': 1,
'b': 2,
'c': 3
};
And you can get or set values by keys:
alert(obj.a); // alerts 1
alert(obj['a']); // same thing
obj['c'] = 4;
In your case Container is function which will build your object. When you do new Container(1, 2, 3); it creates an empty object, and execute the function in the context of the object.
function Container(x, y, z){
this.x = x;
this.y = y;
this.z = z;
}
// There is no point to put parameters there since they are already instance variables.
Container.prototype.sumUp = function addUp(){
alert(this.x + this.y + this.z);
};
container_instance = new Container();
container_instance.sumUp();

Categories