Search code examples
javascript-objects

Javascript object.creation problem in particular example


Most likely a noob question, but after reading about component paradigm with javascript I was trying to build a simple component system for learning purposes.

After a while I come to something like the code bellow where different instances of the Base object should hold several components in its _Comp member -Using just one here for clarity-, to easily cicle them and ask if a component is present or not:

    // Base
    const Base = {
        _sName:"",
        _Comp:{},           // To store components
    };

    // Component
    var Component = {
        Constructor:function( MyBase )
        {
            this._MyBase = MyBase;
        }
    };

    // Factory
    function CreateBase( sName )
    {
        let MyBase = Object.create( Base );
        MyBase._sName = sName;

        MyBase._Comp.Component = Object.create( Component );
        MyBase._Comp.Component.Constructor( MyBase );
        return MyBase;
    };

    // Create test Bases

    var A = CreateBase( "A" );
    var B = CreateBase( "B" );

    console.log( A._Comp.Component._MyBase._sName );
    console.log( B._Comp.Component._MyBase._sName );

As you can see I want the components to have a reference to their Base holder to be able to access the Base within the component functions.

But When running this code both of the final logs output "B".

I was expecting "A" and "B". But somehow the CreateBase("B") is overwriting also the component objects previously added to A. I'm trying to figure why this happens, and a valid/proper way to do something like this.

Any help would be appreciated.


Solution

  • Base is being used as the prototype for both objects. Since neither have their own _Comp property, changing _Comp on either will change it on Base, not the inherited objects. To have the objects encapsulate their own properties, define them for each one:

     // Base
        const Base = {
            _sName:"",
            _Comp:{},           // To store components
        };
    
        // Component
        var Component = {
            Constructor:function( MyBase )
            {
                this._MyBase = MyBase;
            }
        };
    
        // Factory
        function CreateBase( sName )
        {
            let MyBase = Object.create(Base);
            MyBase._sName = sName;
            MyBase._Comp = {}; //Define _Comp on MyBase so any changes go here.
    
    
            MyBase._Comp.Component = Object.create( Component );
            MyBase._Comp.Component.Constructor( MyBase );
            return MyBase;
        };
    
        // Create test Bases
    
        var A = CreateBase( "A" );
        var B = CreateBase( "B" );
    
        console.log( A._Comp.Component._MyBase._sName );
        console.log( B._Comp.Component._MyBase._sName );