Objects within the Prototype in Javascript

While delving into the world of AngularJS, I stumbled upon an interesting revelation - when objects are placed in a prototype object, any instances inheriting from that prototype will alter the prototype's objects upon assignment.

For example:

function Person(name) {this.name = name;}
Person.prototype = {species : "homo-sapiens" , characteristics : { "legs" : 2 , "height" : 175}}
var joe = new Person("joe"); 
joe.characteristics.legs = 1; 
console.log(Person.prototype.characteristics) //Object {legs: 1, height: 175}

What this demonstrates is that the instance (in this case, 'joe') associated with the prototype altered the value of the object on the prototype itself because it inherited an object ('characteristics'), as opposed to a primitive value.

So, the question arises: Should prototypes primarily contain primitive values? In most scenarios, you would not desire an instance to modify the prototype's value. However, Angular.js allows for this behavior, albeit in rare cases where a child instance needs to write to the prototype.

If you do wish to place an object on the prototype without allowing instances to overwrite its properties upon assignment, what approach could be taken?

Answer №1

Although this isn't directly related to the concept of prototype, it does showcase a common JavaScript behavior.

To resolve this issue, you can replicate the object from the prototype within the constructor:

function Person() {
    this.characteristics = Object.assign({}, this.characteristics);
}

Person.prototype = { whatever };

The code snippet above assumes that you have access to the Object.assign method for object copying. Otherwise, you would need to manually copy the object by iterating through its properties and creating a duplicate.

Answer №2

If you want to achieve the desired behavior, consider implementing the following:

function Individual(name) {
    this.name = name;
    this.type = "human";  
    this.attributes = { "legs" : 2 , "height" : 175};
}
// NOTE: The line below is no longer necessary, but included for reference
Individual.prototype = {type : "human", 
                    attributes : { "legs" : 2 , "height" : 175}}

var person = new Individual("John"); 

person.type = "ordinary human being"; 
console.log('Individual.prototype.type:', Individual.prototype.type); 
// Output: Individual.prototype.type: human
console.log('person.type:', person.type); 
// Output: person.type: ordinary human being

person.attributes.legs = 1 ; 
console.log('Individual.prototype.attributes:', Individual.prototype.attributes); 
// Output: Object {legs: 2, height: 175}
console.log('person.attributes:', person.attributes); 
// Output: Object {legs: 1, height: 175} 

Your inquiry doesn't directly relate to Angular; it pertains more to JavaScript's prototype-based inheritance concept.

You might find this article on prototypical inheritance helpful.

Additionally, you can refer to this Stack Overflow discussion on __proto__ versus prototype.

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

Challenges with differentiating between addition and concatenation in Vue computed properties

Recently diving into Vue and came across an intriguing issue, I am curious to know the reason behind it and how to prevent it. <template> <div> <input type="number" v-model="a" style="color: white" /> <input type="number" v- ...

What could be causing the issue of the view not showing up in AngularJS?

I've been trying to use AngularJS modules to display a view, but for some reason my page isn't showing up. Can anyone help me figure out what's going on? You can check out my code at the following link: <!DOCTYPE html> <html> & ...

Vue - Enhanced Image Cropper (Error: Unable to retrieve image result from this.$refs.cropper)

I have a crop function for Vue Advanced Cropper similar to the one below: crop() { const { canvas } = this.$refs.cropper.getResult(); if (canvas) { const form = new FormData(); canvas.toBl ...

What is the best way to switch between components in vue.js?

I have created a Dashboard.vue component consisting of two child components: DisplayBooks.vue and sortBooksLowtoHigh.vue. Initially, the sortBooksLowToHigh component is hidden while the displayBooks component is visible by default. The requirement is that ...

Exploring JQuery and JavaScript for loop guide

Currently working on a small application where users are required to input information, and I am implementing text hints in the input fields. However, I have encountered an issue when using a for loop in my code. Oddly enough, the text hints display corre ...

Unable to transform Symbol data into a string - Error when making a React AJAX delete call

I'm encountering an issue where I am getting a Cannot convert a Symbol value to a string error in the console. My tech stack includes React v15 and jQuery v3. https://i.stack.imgur.com/qMOQ8.png This is my React code snippet: var CommentList = Reac ...

Transforming data with D3.js into a string representation

Recently, I stumbled upon a function called "stringify" that seems like a fantastic tool for converting flat data into a Json format. If this function lives up to its potential, it could potentially save me countless hours of writing recursive code in ASP ...

The angular event broadcaster controller is currently unavailable

In my app, there is a search box and a list of results. The search box is controlled by SearchCtrl, while the list of results is managed by DocListCtrl. When a user submits a query, SearchCtrl emits an event that DocListCtrl listens for in order to update ...

Unit Testing with Jest: Testing the Invocation of a Function within a Nested (Asynchronous) Function

Attempting to create a unit test for a nested function, here is the structure: myFunction.js const anotherFunction = require('./anotherFunction.js') module.exports = (app, io) => { return (req, res) => { const { id, value } = req.q ...

Locate a specific item in an array using AngularJs based on a key and present its value on the View

Imagine you have an array of objects: $scope.objArr = [{key:1,value:'value1'},{key:2,value:'value2'},{key:3,value:'value3'}]; And a variable that corresponds to key. For instance: $scope.a = 3; In the Controller, you want ...

What is the method used by Bootstrap to create a darker page background behind a modal?

I am struggling to understand how Bootstrap darkens the background of a page when a modal is displayed. Even though a class is added to the body tag (modal-open), the effect on the background isn't clear to me. Learn more about Bootstrap modals here ...

Extract the label from Chip component within the onClick() event in material-ui

-- Using Material-UI with React and Redux -- Within my material-ui table, there are <TableRow> elements each containing multiple <TableCell> components with <Chip> elements. These <Chip> components display text via their label prop ...

When onSubmit is triggered, FormData is accessible. But when trying to pass it to the server action, it sometimes ends up as null

I am currently utilizing NextJS version 14 along with Supabase. Within my codebase, I have a reusable component that I frequently utilize: import { useState } from 'react'; interface MyInputProps { label: string; name: string; value: stri ...

When using threejs, the color set for setClearColor is supposed to be white. However, when calling an external HTML file, it unexpectedly renders as

When I call an external HTML file in Three.js, the value for setClearColor is white but it renders as black. How can I solve this issue? Click here to view the image Here are the codes from the external file: <div id="3d-modal"></div> <sc ...

Showing AngularJS information on Views

After successfully implementing static HTML with views, as shown in this example: https://embed.plnkr.co/MJYSP01mz5hMZHlNo2HC/ I am now facing a challenge with integrating the angular-ui accordion within ng-view. You can view the accordion I am attemptin ...

Retrieval of entity through REST Endpoint using ODataSetName for Custom Entity

In my restendpoint.js file, I have a function called retrieveRecord which is defined on this website I am working on a function that should trigger whenever the Programme (a lookup field) on the Application entity changes. The goal is to fetch the attribu ...

The plugin "react" encountered a conflict while trying to sync with both the "package.json" and the "BaseConfig" files

Whenever I open Terminal in my react folder and try to start the react app using npm start, I always end up encountering an error on the browser. The error message states that the "react" plugin is conflicting between two paths: "package.json » eslint ...

Greetings: Obtaining an array of text within the <td> tags

Here is the HTML Source: <td bgcolor="#ffffbb" colspan=2><font face="Verdana" size=1>2644-3/4<br>QPSK<br><font color="darkgreen">&nbsp;&nbsp;301</font> - 4864</td> I am looking to extract text array wit ...

Mastering the art of correctly utilizing splice and slice

I'm having trouble identifying the issue in my code. Despite reading numerous articles on slice and splice, I am unable to achieve the desired outcome in my Angular project (not using both methods simultaneously). The results are not as expected. Belo ...

Creating uniform line lengths with a ruler utilizing Fabric.js

I have a div that scrolls horizontally and contains a ruler div and a canvas where I draw horizontal lines of varying lengths. When drawing the lines, I want to ensure they are accurately measured against the ruler using JavaScript and CSS: var canvas = ...