Setting the prototype attribute to the object's attribute in JavaScript

Initially, I have some confusion regarding the prototypal structure of Javascript which might make this task challenging.

Suppose I have ...

var vector = function( x, y ) {
    this.x = x || 0;
    this.y = y || 0;
}

var obj = function() {
    this.position = new vector( 0, 0, 0 );
}

var cube = new obj();

... how can I include a property x to obj that allows calling cube.x to be the same as cube.position.x. I believe it's possible to link properties of each other, but I am uncertain about the syntax. Something like obj.prototype.x = obj.position.x is ineffective because obj.position is undefined.

I desire the following functionality

alert(cube.position.x); // 0
alert(cube.x); // 0

cube.position.x = 2;
alert(cube.position.x); // 2
alert(cube.x); // 2

cube.x = 4;
alert(cube.position.x); // 4
alert(cube.x); // 4

Is this feasible?

It's worth mentioning that I am using Three.js, so modifying the objects completely is not an option; I can only add to them and their prototypes.

Answer №1

If you want cube.x to reflect the value of cube.position.x, you'll need to create accessors and mutators for obj.prototype.x. These features in JavaScript are a more recent addition and may not be compatible with older versions of IE.

var vector = function( x, y ) {
    this.x = x || 0;
    this.y = y || 0;
}

var obj = function() {
    this.position = new vector( 0, 0, 0 );
}
obj.prototype = {
    ...your prototype methods here...
};
Object.defineProperty(obj.prototype, 'x', {
    get: function () {
        return this.position.x;
    },
    set: function (val) {
        this.position.x = val;
    }
});

//Alternatively:
obj.prototype = {
    get x() {
        return this.position.x;
    },
    set x(val) {
        this.position.x = val;
    }
};

var cube = new obj();
cube.x; //0
cube.x = 10;
cube.position.x; //10

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

Step-by-step guide on uploading a template in unlayer-react-email-editor

<EmailEditor ref={emailEditorRef} onReady={onTemplateReady} /> const onTemplateReady = () => { try { const templateJson = htmlToJSON(savedData?.email?.content); console.log({ templateJson }); emailEditorRef?.current?.editor?. ...

What is the method to retrieve the color of a linearGradient in an SVG at a particular

I am working on a unique progress bar that uses a linear gradient and a small ellipse to indicate the completion percentage. The AngularJS binding updates the completion percentage and a function is called. My challenge is to change the color of the ellip ...

Utilizing jQuery to compute dynamic fields depending on selection in a dropdown menu

Creating a Ruby app for tracking bets, I have designed a small form that captures various details including date and match. However, the most crucial components of this form are the "stake" and "odd" text fields. To enhance user experience, I have incorpor ...

What are the steps for implementing videojs vr in a Vue.js project?

After installing the videojs vr with npm install --save videojs-vr, I attempted to use it in my project: https://i.stack.imgur.com/lSOqF.png However, I encountered this error message: https://i.stack.imgur.com/QSe1g.png Any assistance would be greatly ...

Developing a custom library to enable Ajax capabilities in web applications

Currently, I am in the process of developing my own personal library. jQuery doesn't quite meet my needs, and I prefer having a clear understanding of what is happening within my code. Nevertheless, I'm encountering an issue with the ajax functio ...

The TypeScript type 'Record<string, string>' cannot be directly assigned to a type of 'string'

I can't seem to figure out why this code isn't working. I've encountered similar issues in the past and never found a solution. The snippet goes like this: type dataType = { [key: string]: string | Record<string, string>; ...

How can HTML and CSS be linked to display images independently?

Check out this code: body{ background-image:url('http://wallpoper.com/images/00/31/33/51/black-background_00313351.jpg'); } div.header{ background-color:#F0F8FF; text-align:center; padding:3px; ...

Create HTML div elements dynamically with JavaScript based on database information

Can javascript be used to create divs from database information? ...

Textfield removal from the input range is requested

I recently encountered an issue with my input range HTML code. Here is the initial code snippet: <input class="sliderNoTextbox" id="ti_monatlich" type="range" name="ti_monatlich" data-theme="d"> After some adjustments based on this helpful answer, ...

Learn how to efficiently pre-load data using the prefetchQuery method in React-Query

Attempting to pre-fetch data using react-query with prefetchQuery. The network tab in browser DevTools shows the requested data coming from the back-end, but strangely, the data is not present in the react-query DevTools cache. Any ideas on what might be c ...

Using Javascript to Implement Pinch Zoom on Android

After searching through the depths of the internet, I have yet to come across a viable solution or answer. The challenge at hand is the need to implement pinch zoom functionality for an element (specifically an image) using JavaScript in a Phonegap environ ...

Steps for inserting new text in front of an element's existing text

Is there a way to insert text before the original content of an element? I know how to add text after using createTextNode, as shown in this example: $("#button").click(function() { $( ".text" ).append( document.createTextNode( " Hello" ) ); }); < ...

Having trouble with JavaScript canvas drawImage function not functioning correctly

Having some trouble drawing part of an image properly. The width and height are not matching the original. Check out my code below: window.onload = function() { ImageObjSketch = new Image(); // URL ImageObjSketch.src = 'https://i.imgur.com/75lATF9 ...

JavaScript function for automatic scrolling to the bottom of the page is not functioning as expected

I'm working on incorporating a terminal/console feature into my website. I came across the JavaScript functions for scrolling down a page, namely window.scrollTo(0,document.body.scrollHeight); and window.scrollTo(0,document.querySelector(".fakeSc ...

Verify the entered information in the input field and showcase it in the display box after pressing the ENTER key

I need to display selected values of a tree structure in a show box on the other side of the page using code. However, I also need to include HTML input boxes in some lines of the tree structure so that users can input data. The challenge is getting the in ...

"Implementing a Texture as Material in Three.js: Step-by-Step Guide

I recently discovered Three.js and I'm really enjoying it. As a newcomer to JavaScript, I'm eager to delve deeper into animation and related topics. //UPDATE I've been working on this code snippet, but unfortunately, it's not functioni ...

Having trouble converting my form data into an array for table display

My website has a form for entering dummy patient information, with a table to display the submitted data. However, I'm facing an issue where the data is not being stored in the array when the user clicks the "Add Patient" button. Upon checking the arr ...

unable to locate the PHP file on the server

Struggling to make an API call via POST method to retrieve data from a PHP file. Surprisingly, the code functions properly on another device without any hiccups. However, every time I attempt to initiate the call, I encounter this inconvenient error messag ...

How can Chrome's display:none latency be eliminated?

My Chrome extension is designed to alter a third-party web page by removing a button and adding two new HTML elements. The process involves observing the URL of the current tab and executing an HTML injection if it matches the specified regex pattern. Desp ...

Tips for setting restrictions on iview ui multiple select feature

How can I add a limit to iView UI's Multiple select? Here is the code snippet: <Select v-model="data.category" :multiple="true" filterable remote :remote-method="remoteMethod2" :loading="loading2"> <Option ...