Is there a way to incorporate a constructor into an arithmetic expression?

I'm looking to streamline my JavaScript code, specifically when it comes to constructors.

Currently, I have a vector defined as:

function Vector2(X, Y) {
    this.x = 0.0;
    this.y = 0.0;

    if (X)
        this.y = Y;
    if (Y)
        this.y = Y;
}

At the moment, if I want to add two vectors together, I have to do the following:

var vector1 = new Vector2(1.0, 0.5);
var vector2 = new Vector2(4.5, 1.0);

vector1.x += vector2.x;
vector1.y += vector2.y;

I'm aiming to make the code cleaner, more readable, and reduce file size when using multiple constructors. My goal is to write something like this:

vector1 += vector2;

Any assistance would be greatly appreciated. Thank you.

Answer №1

Here is a possible solution:

function Vector(X, Y) {
    this.x = X || 0.0; // I made your constructor simpler
    this.y = Y || 0.0;
}
Vector.prototype.add = function(v) {
   this.x += v.x;
   this.y += v.y; 
}

Usage would be as follows:

var vector1 = new Vector(4,4);
var vector2 = new Vector(1,3);
vector1.add(vector2);

Answer №2

result = vector1 + vector2;

It seems like you may be mistaken about being able to override operators in JavaScript. Can you provide more details about where you heard this information?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Cypress eliminating the "X-CSRFToken" header

There seems to be an issue with the Cypress test runner where it is removing X-CSRFToken from the request header, leading to a 403 Forbidden error. I have compared the headers between a manual run and a Cypress test run, and you can see the difference in t ...

Why is the jQuery class not responding to the is(:visible) selector?

Having trouble with this issue, I created a fiddle to demonstrate what I'm trying to achieve: http://jsfiddle.net/x2btM/9/ Below is the code snippet: <div id="ZodOneDragBox"> <div id="aquariusSelectedComp1" class="killSelectedComp1" sty ...

Use jQuery to detect the presence of the class .class, and if it exists, automatically append the same class to a specific #id element on a particular webpage

Need help with jQuery - adding a specific class to an element based on the presence of another class Hello everyone, I have searched through various forums and tried multiple code snippets in JavaScript and jQuery to no avail. Despite other scripts worki ...

The first time I tried using React-app, I encountered an error that read "[email protected] postinstall"

I've been struggling to set up create-react-app, encountering the same issue repeatedly. I tried uninstalling and reinstalling node.js, but only the package.json and my-app folder were created. No src or other required folders were generated. Termina ...

Display complete information of the selected list in a modal window by clicking on it in PHP Yii

I recently started working with the Yii framework and encountered a challenge when trying to pass data from a list to a modal using AJAX. The modal is located within the same view as the list. Here's a snippet of my code: This is my view: <div id ...

Troubleshoot: Unable to send or receive messages in Socket.IO Chat

I recently tried following a tutorial on socket.io chat, which can be found here. Although the tutorial video showed everything working perfectly, I have encountered issues with my implementation. It seems like the messages are not being sent or received ...

Sorting complex functions in React with Javascript

Looking to implement a sorting function that switches between descending (dsc) and ascending (asc) order. It should specifically handle sorting by the table column named "header". The objective is to sort either by "days" or "station" while toggling betwee ...

Issue with toLocaleString() function not functioning correctly within a Pug template

I have been attempting to utilize the toLocaleString() function in my Pug view. It seems to work fine when no arguments are provided, defaulting to 'en-US', regardless of the browser's language settings. While this is acceptable, I am intere ...

Can we call a function in a directive from a view?

I'm still learning the ropes of AngularJS and am eager to gain hands-on experience. In my HTML file, I have a directive containing a function that I want to call from the view. The code snippet looks like this: <div collapse class="collapsed" ng- ...

What are the steps to check Drag and Drop functionality using Selenium IDE?

I've been working on implementing tables with jQuery UI's sortable feature, but I'm struggling to come up with a way to test it using Selenium IDE. After searching for a solution, I came across this helpful post: How to test a JQuery UI Sor ...

Having trouble with loading image textures in three.js

Here is the code snippet I am using: var scene = new THREE.Scene(); // adding a camera var camera = new THREE.PerspectiveCamera(fov,window.innerWidth/window.innerHeight, 1, 2000); //camera.target = new THREE.Vector3(0, 0, 0); // setting up the renderer ...

The execution of JavaScript fetch is experiencing a delay

My website is equipped with an Express server that is ready to execute a shell script when triggered. However, there is a delay in running the shell script as it waits for the user to accept or deny a "confirm window." I am looking for a way to prompt the ...

Angular - Execute a function once the observable has finished

I am currently working with a 2 part process that involves importing a list of usernames in Component 1, submitting it to a service, and then using the returned user profile data in Component 2. The issue I am facing is that when I receive the data back f ...

Is dirPagination failing to display pagination links correctly?

I am currently attempting to implement server-side pagination in my application, but I am facing challenges as the paging option seems to be missing. I have been following this tutorial for guidance. Below is a snippet of my code: JavaScript: $scope.vm= ...

CORS preflight request in Express.js was unsuccessful even after enabling CORS

Currently, I am utilizing a self-signed SSL certificate to operate an HTTPS server using Express. Below is my app.js code: const express = require('express'); const BodyParser = require('body-parser'); const config = require('./co ...

How can I identify a pattern in JavaScript that may include a certain character but cannot end with it using regex?

I am a beginner in the world of regular expressions. Despite my efforts to find a solution for my specific case, I have not been successful. I have tested several ideas that I came across, but none of them have worked for me. I have a unique repetitive pa ...

The ajax datatable is refusing to trigger the php file, despite my attempts at implementing various solutions that have all proven

This is the feature I use to retrieve data from a PHP file and display it in a table format. <script type="text/javascript" language="javascript" > $(document).ready(function(){ fetchData(); function fetchData() { var dataTable = $(&apos ...

What is the most efficient way to use the $slice operator on a highly nested array in mongoose

I am currently working on slicing a deeply nested array. To illustrate, consider the following structure. I aim to slice this array for pagination purposes. {messages: [{ message: { members: [ {example: object, blah: blah}, {example2: object2, blah2: blah ...

UI-Router is malfunctioning, causing ui-sref to fail in generating the URL

I'm currently working on a project that involves Angular, Express, and UI-router for managing routes. While I've properly configured my $states and included the necessary Angular and UI-router libraries in my HTML file, I am facing an issue wher ...

Switch between MMM dd yyy and dd/mm/yyyy date formats easily

I have implemented a native material-ui date picker which currently displays dates in the dd/mm/yyy format. However, I need to customize the display format to show dates like this: Jun 18 2012 12:00AM. This specific date format is essential for consistency ...