Search code examples
javascriptprototypejscript

JScript oject A using object B don't see it's functions


Got two Javascript files, lets say A and B.

One included into the other - B uses object from A file.

In my debug function first I create AConfig object, then I create BElementBuilder, which uses ABuilder and AConfig object;

Everything is ok at the moment.

But then, when I call bElement.getBString it goes inside and fails on me.aBuilder.getAString(Aconfig); with error

object doesn't support this property or method

Why is this happens?

Here's A

var AConfig = (function() {
    function AConfig(name, flag){
        this.name = (name) ? name : -1;
        this.flag = (flag) ? true : false;

        return this;
    }   

    return AConfig;     
})();

var ABuilder = (function() {
    function ABuilder(config){
        this.config = (config) ? config : new AConfig();

        return this;
    };

    ABuilder.prototype = {
        getAString: function(configObj){
            var me = this,
                config = (configObj) ? configObj : me.config,
                name = me.name,
                flag = me.flag;

            return 'A name is' + name + 'flag =' + flag;
        }
    }

    return ABuilder;
});

Here's B:

!INC aFile.A

   var BElementBuilder = (function() {
        function BElementBuilder(aConfig, bName){
            this.aConfig = (aConfig) ? aConfig : new AConfig();
            this.bName = (bName) ? bName : "B";
            this.aBuilder = new ABuilder();

            return this;
        };

        BElementBuilder.prototype = {
            getBString: function(configObj){
                var me = this,
                    Aconfig = (configObj) ? configObj : me.aConfig,
                    name = me.bName;
                //and here it fails 
                Aconfig = me.aBuilder.getAString(Aconfig);

                return 'B has config of' + Aconfig;
            }
        }

        return BElementBuilder;
    })();

    function debug(){
        var aConfig = new AConfig("AAA", true);
        var bElement = new BElementBuilder(aConfig);

        var t = bElement.getBString(aConfig);
    };

    debug();

P.S. It's JScript if it makes any difference


Solution

  • You forgot the IIFE invocation on your ABuilder module. That way, ABuilder is not the class constructor, but rather the module factory function which returns a new constructor function. When you call it as new ABuilder();, it will return such a constructor function that gets assigned to the bElement.aBuilder, instead of the isntance you expected.