Exchange of arrays between basic classes is made possible with ExtJS

I have two subclasses that inherit from a parent class.
Class1 inherits from BaseClass Class2 inherits from BaseClass I create instances of both classes.
When I display the array content of Class2, I see the contents of Class1 as well.

http://jsfiddle.net/k3emY/2/

Ext.onReady(function () {
   var c1 = Ext.create('Child1Class');    
   var c2 = Ext.create('Child2Class');
   alert(c2.someArray.join());  
   //actual result: "BaseClass text ,Class1 text,Class2 text"
   //expected :"BaseClass text ,Class2 text"
});


Ext.define('BaseClass', {
    someArray: ["BaseClass text "],
});

Ext.define('Child1Class', {
    extend : 'BaseClass',
    constructor : function(){
        this.someArray[this.someArray.length] = "Class1 text";
    }
});

Ext.define('Child2Class', {
    extend : 'BaseClass',
    constructor : function(){
        this.someArray[this.someArray.length] = "Class2 text";
    }
});

Why is Class1's data also included in the output?

Answer №1

someArray is a property that belongs to the prototype of BaseClass. Inheritance in JavaScript allows for shared properties among subclasses and instances, which can lead to unexpected behavior. To prevent this, it's recommended to declare the array within the constructor function. For instance, consider the following simplified example:

function Class() {}
Class.prototype.array = [];

var c1 = new Class();
var c2 = new Class();
c1.array.push('a');
c2.array; // ["a"]

This concept is similar to:

var array = [];
var c1 = { array: array };
var c2 = { array: array };
c1.array === c2.array; // true

By utilizing a constructor function:

function Class() {
    this.array = [];
}

var c1 = new Class();
var c2 = new Class();
c1.array.push('a');
c2.array; // []

A more concise version of the same scenario:

var c1 = { array: [] };
var c2 = { array: [] };
c1.array === c2.array; // false

Answer №2

Because each instance shares the same array, you can avoid this by creating a new array for each instance like in this example:

Ext.onReady(function () {
    var c1 = Ext.create('Child1Class');
    var c2 = Ext.create('Child2Class');

    alert(c2.someArray.join());
});

Ext.define('BaseClass', {
    constructor: function (config) {
        this.callParent(arguments);

        Ext.apply(this, {
            someArray: ["BaseClass content "],
        });
    }
});

Ext.define('Child1Class', {
    extend: 'BaseClass',
    constructor: function () {
        this.callParent(arguments);

        this.someArray[this.someArray.length] = "Class1 content";
    }
});

Ext.define('Child2Class', {
    extend: 'BaseClass',
    constructor: function () {
        this.callParent(arguments);

        this.someArray[this.someArray.length] = "Class2 content";
    }
});

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

Using unseralize in PHP allows you to transform the initial data into a different format

I have a string that needs to be unserialized in order to get the original values. $string3 = 'a:3:{i:0;a:2:{s:5:"value";d:4.0999999999999996;s:7:"players";a:2:{i:6;i:6;i:7;i:7;}}i:1;a:2:{s:5:"value";d:10.899999999999999;s:7:"players";a:1:{i:7;i:7;}} ...

"Encountered an error while trying to access properties that

Struggling to create a practice menu with the functionality of making elements appear and disappear on click? If you are encountering issues with a class named "option" not working as expected, you are not alone. Clicking on nested objects like images or i ...

Angular Transclude - ng-repeat fails to iterate over elements

Recently, I've been experimenting with Angular directives and encountered a peculiar issue... Check out the code snippet below: <!DOCTYPE html> <html> <head> <title>Directive test</title> <script type="text/ja ...

Exploring the world of Palindromes and Arrays: an adventure in exasperation

I am currently working on a Palindrome Checker using arrays that are categorized as Clean or Dirty. While the code compiles successfully, I am encountering issues when attempting to identify actual palindromes. Displayed below is the specific code in ques ...

React-onclickoutside does not function properly within an iframe

I have developed a custom drop-down list using reactjs. I utilized react-onclickoutside to recognize clicks outside the list and close it. While this method works effectively, it does not respond to clicks within an iframe. import onClickOutside from &apo ...

Display or conceal certain HTML form elements based on the selection made in the previous form element

I need assistance with a function that can dynamically show or hide certain HTML form elements based on the user's previous selection using JavaScript. For example, if a user selects "Bleached" from the Dyingtype drop-down menu, there is no need to di ...

Having an issue with the return function in a jQuery $.ajax call

I am currently working with a $.ajax call that is structured like this: <script type="text/javascript"> $(document).ready(function () { $('#add_com_frm').submit(function (e) { e.preventDefault(); var $b ...

Breaking up a string using regex with various conditions

(Javascript old version of Node.js) Update: I need to clarify my request. I have a variety of instances like these var name1; CONST name2 Let nam; leT nam VAr n1 ; What I want as output is name1 name2 nam nam n1 Therefore, I am ex ...

Tips for finding the index of data in Cesium

After successfully completing the tutorial on building a flight tracker, I am facing a challenge. I want to access the current index of my data at any given time while my app is running cesium and displaying the airplane animation following the flight path ...

Updating $scope in AngularJS works in JavaScript, but the changes are not reflected in the HTML

After making a request to the server and receiving a correct response, I have an array of objects called $scope.photos. However, when attempting to add a new photo by sending a request and then trying two different methods to update the $scope in the HTML, ...

Efficiently sanitizing a JavaScript object using the replace() method in JavaScript

I have a data object structured like this {"paymethod_id":1,"business_id":76,"delivery_type":"1","driver_tip":0,"delivery_zone_id":6569,"delivery_datetime":null,"location":{&qu ...

When using Vuejs2, the list of autosize textareas connected to an expanding array of objects does not properly update their values

After binding https://github.com/jackmoore/autosize to textareas within a v-for loop, I've noticed an unexpected data persistence issue while expanding the array linked to that list: While inputs on the left side move downward as intended, new textar ...

Binding an event to an Angular 2 component directly within its selector code

Looking at my Angular 2 component: import { Component, ElementRef, Renderer } from '@angular/core';; @Component({ selector: 'my-button', templateUrl: 'button.html' }) export class ButtonComponent { private text: string ...

Is it best practice to initialize loaded scripts before the JQuery .load callback is called or should it be done after the .ready callback in the loaded script?

When I click a button in my main document, I load the content of a specific div using jQuery: $("#my_div").load(function() { alert("Content Loaded"); }); The loaded content contains a script: <script> alert("Initial Alert from External Script" ...

There appears to be an issue with the error handling function within React

I am facing an issue with my error function while checking the browser error, and I am unsure why adding a console.log with the error is causing trouble. I need some assistance in troubleshooting this problem which seems to be occurring at line 29 of my im ...

Issue with displaying the file-field in Django admin after upgrading from Django 2.1 to version 3

Since upgrading from Django 2.1 to 3, the file field in Django admin is now displaying as "loading". https://i.sstatic.net/8JDWu.png An error is appearing in the console. https://i.sstatic.net/RCgwt.png https://i.sstatic.net/78YtG.png Previously, ther ...

What is the best way to create a promise in a basic redux action creator?

My function add does not return any promises to the caller. Here's an example: let add = (foo) => {this.props.save(foo)}; In another part of my application, I want to wait for add() to finish before moving on to something else. However, I know t ...

method for sorting labels in Select element in ReactJS

Hey there, I'm facing an issue with the code snippet available here. I would really appreciate it if you could assist me in resolving this problem. This is the code: import React from "react"; import { Select } from "antd" ...

What is the best way to transfer information between two views in Aurelia?

I have two different perspectives, one called logo and the other called folder. The logo view should display something from the folder view if the folder is empty. logo.html <template> <require from="company-assets/folders"></require> ...

JavaScript function to provide a range of numbers based on a specified number and step value

I am looking for a solution to dynamically generate content based on the number of slides/steps using JavaScript. Any suggestions on how to best achieve this? Thanks in advance! switch(this.currentSlide) { case 1: return '1-12'; ...