Search code examples
javascriptjavascript-objects

Why i can't access an object created in a method of an object


Let's say i have this code:

var m = 
{
    init: function(num, num2, num3)
    {
        this.num = num;
        this.num2 = num2;
        this.num3 = num3;
    }
};

var t = 
{
    create: function()
    {
        var obj = Object.create(m);
        obj.init(1,2,3);
    }

};

t.create();
console.log(obj)

When executing this code i get this error:

obj is not defined

How can I make obj work outside the method create ?


Solution

  • Change your create function to return the obj. Then, you can do var obj = t.create().

    Here is the complete code:

    var m = 
    {
        init: function(num, num2, num3)
        {
            this.num = num;
            this.num2 = num2;
            this.num3 = num3;
        }
    };
    
    var t = 
    {
        create: function()
        {
            var obj = Object.create(m);
            obj.init(1,2,3);
            return obj;
        }
    
    };
    
    var obj = t.create();
    console.log(obj)