There seems to be something off with the behavior of my object-oriented programming

Trying to grasp OOP in JS has been quite challenging for me lately... Here is my attempt so far:

var worldClass = function(shape){
            this.shape = shape;
            switch (shape){
                case "sphere":
                    var tmpX = new THREE.Vector3(0, 0, 0);
                    var sphereModel = new THREE.Sphere( tmpX, 6);
                    var sphereGeom =  new THREE.SphereGeometry( 6, 32, 16 );
                    var boundMaterial = new THREE.MeshBasicMaterial( { color: 0x0000ff, transparent: true, opacity: 0.3 } );
                    var boundSphere = new THREE.Mesh( sphereGeom, boundMaterial );
                    boundSphere.position.set(tmpX);
                    break;
                default:
                    var tmpX = new THREE.Vector3(0, 0, 0);
                    var sphereModel = new THREE.Sphere( tmpX, 6);
                    var sphereGeom =  new THREE.SphereGeometry( 6, 32, 16 );
                    var boundMaterial = new THREE.MeshBasicMaterial( { color: 0x0000ff, transparent: true, opacity: 0.3 } );
                    var boundSphere = new THREE.Mesh( sphereGeom, boundMaterial );
                    boundSphere.position.set(tmpX);
                    break;
            }

            this.home = boundSphere;

            this.draw = function(){
                scene.add(this.home);
            }

            this.setPosition = function(newPos){
                this.home.position.set(newPos);
            }
        }

        var world1 = new worldClass(new THREE.Vector3(0, 0, 0));
        console.log(world1.home.position);
        world1.setPosition(new THREE.Vector3(1, 1, 1));
        console.log(world1.home.position);

The initial output I receive is : undefined, and when attempting to change the position, I encounter undefined fields instead of

x: undefined, y:undefined, z:undefined
.
I realize I could use a property to resolve this issue, but I am determined to understand what's wrong with my class.
I've managed to work around this by adding a "constructor" function to the class, which encapsulated the seemingly problematic line:
this.position = new THREE.Vector3();
. However, I still yearn to comprehend the correct approach to handling classes in JS.

Answer №1

When you call setPosition with a Vector3, it actually only sets position.x to that value...

For a solution, check out this link: http://codepen.io/snovak/pen/OMMoNZ

        this.setPosition = function(newPosition){
            if(newPosition.hasOwnProperty("x") && newPosition.hasOwnProperty("y") && newPosition.hasOwnProperty("z") ){
               this.home.position.set(newPosition.x, newPosition.y, newPosition.z ) ;
            } else {
              console.log("setPosition requires THREE.Vector3 as argument");
            }               
        }

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

There seems to be an issue with the conversion of GLTF

Exploring the world of threejs in react has been quite an adventure for me. I discovered that the key to displaying 3D objects in react is by converting them into a JSX Component using gltfjsx. Following the procedure, I tried working with both glb and glt ...

How Keyof can render an object undefined and prevent accurate verification

Encountering TS2532 error: Object is possibly 'undefined' while attempting to access an object's value by dynamically selecting the key. TypeScript seems to be restricting me from checking the field values, and I'm unsure of the underly ...

How can you switch the property of an object in VueJS?

I am currently working with an array called cars, which contains names of cars as well as a property called starred. My goal is to toggle the value of starred between true and false for each car, ensuring that only one car can have starred set to true at a ...

What is the NodeJs Event loop and how does it work with libuv and V8

NodeJs is made up of the V8 engine and the libuv library. The V8 engine has its own event loop with a call stack, event queue, and micro task queue to run our main code. The libuv also has an event loop with phases like times, callbacks, poll, check, and ...

Troubleshooting: AngularJS Form Submission Failure

As a novice in Angular and not a JavaScript expert, I am facing challenges with form submission. My task involves loading movie showtimes from an http API and using ng-repeat to display them within a page container. The REST API requires a zipcode input, w ...

Exclude objects with similar ids using a method other than JavaScript's filter()

I have a list of students who need to receive medication multiple times throughout the day. The challenge is to filter the array to track how many times each student receives the same medication. The list includes three different students and repeats the s ...

Generate slanted projection mapboxgl

Trying to develop a building simulator based on zoning codes. I can measure values, create floors, but struggling to extrude diagonally or create a perpendicular plane to the floor for evaluating angles from the street to limit building height (see image 2 ...

Pressing the reset button on a basic calculator

I am experiencing an issue with my calculator. It works fine initially, but after using the reset button, it stops functioning properly. Currently, I only have the multiplication set up as I debug this problem. I am new to JavaScript and would appreciate a ...

Switch from buffer to base64 encoding for viewing in Angular

Hello, I have developed an application using the MEAN stack. Currently, I am facing an issue with retrieving images from my endpoint. The image array values that I am receiving look like this: 8,8,7,7,9,8,9,8,9,8,9,9,8,8,8,8,7,9,7,7,9,10,16,13,8,8,16,9,7, ...

Error: Request for resolution of all parameters for SignupComponent failed: ([object Object], ?). Occurred at the syntaxError in compiler.js:2175

Could someone assist me in resolving this issue? signup.component.html <main role="main" class="container> <h1 class="mt-5">&nbsp;</h1> <h5 class="mt-5 ">Create Account</h5> <br/> <div class="loa ...

Create efficient images using Node.js and express using sharp or canvas

Struggling with optimizing image rendering using node, express, and sharp. Successfully implemented an upload method with Jimp for images over 2000px wide and larger than 2mb in file size. While many libraries can achieve this, Jimp was more memory-effici ...

SCORM: moving between SCOs by clicking a button in the presentation

Currently, I am developing a website that allows users to create presentations. One of the website's features is the ability to export presentations in SCORM format (either 1.2 or 2004). This is my first time working with SCORM and I am currently impl ...

When trying to serialize elements from a form loaded by Firefox using AJAX, encountering difficulties due to

Visit the live version of this at . When prompted for a formId, input BroadRunTrack2013. Follow by adding an item to cart and entering player name information (you can use random data for now). Select the Runner's Hat, choose color/size, specify quant ...

Discovering a specific URL link element within the DOM using webdriver.io

I am currently utilizing webdriver io for conducting tests on a webpage. I am in need of verifying the existence of an element with a specific href on the page. I have attempted to achieve this using the following snippet var client = webdriverio.remote ...

Enhancing Donut Chart with d3.js

After working for several hours, I'm having trouble getting my d3.js donut graph to update with new data. Here's my HTML: <body> <div id="pie"></div> <script src="pie.js"></script> </body> And he ...

Exploding particles on the HTML5 canvas

I've been working on a particle explosion effect, and while it's functional, I'm encountering some issues with rendering frames. When I trigger multiple explosions rapidly by clicking repeatedly, the animation starts to lag or stutter. Could ...

Building a custom search modal using RenderPartial in Yii

I'm currently working on developing a modal box that will enable users to filter and search through a grid. The main objective is to allow users to retrieve information from one database while simultaneously completing a form in another database. Alt ...

Is there a way to adjust this callback function in order to make it return a promise instead?

This script is designed to continuously attempt loading an image until it is successful: function loadImage (url = '', callback = () => {}) { utils.loadImage(url, () => { callback() }, () => { loadImage(url, callback) }) } ...

Utilize ES6 to import components for rendering on the server-side

In my ES6 React component file, I have a simplified version that utilizes the browser-specific library called store. Everything works perfectly fine on the browser: /app/components/HelloWorld.js: import React, { Component } from 'react'; import ...

Seeking assistance with importing Json data into my HTML page using Python and AJAX

I've recently started delving into the world of AJAX and it's been quite some time since I last worked with JS. Currently, I'm using Python to generate valid JSON data, but my understanding hits a wall after that step. When I inspect the ele ...