Sumit Deshpande Sumit Deshpande - 22 days ago 4
Javascript Question

How to access object properties from prototype in javascript?

I have class below when I call printData I get this.collection is undefined.

How do I access this.collection from the prototype inside printData()? Or do i need to change the class structure. Actually the object returns function which intern returns object in hierarchy.

Thanks in advance!

Sample Class:

var DbProvider = (function () {
function DbProvider(db) {
var that = this; // create a reference to "this" object
that.collection = db;
}
DbProvider.prototype.create = function () {
return {
action: function () {
var y = {
printData: function () {
alert('Hello ' + this.collection.Name);
}
};
return y;
}
};
};
return DbProvider;
})();


Usage:

var a = new DbProvider({ "Name": "John" });
a.create().action().printData();

Answer

You could save the this reference and bind it to the printData function

var DbProvider = (function () {
    function DbProvider(db) {
        var that = this; // create a reference to "this" object
        that.collection = db;
    }
    DbProvider.prototype.create = function () {
        var self = this;
        return {
            action: function () {
                var y = {
                    printData: function () {
                        alert('Hello ' + this.collection.Name);
                    }.bind(self)
                };
                return y;
            }
        };
    };
    return DbProvider;
})();

var a = new DbProvider({ "Name": "John" });
a.create().action().printData();

Or you could refactor a bit and move that to the outer scope of DbProvider and use that in printData

var DbProvider = (function () {
    var that;
    function DbProvider(db) {
        that = this; // create a reference to "this" object
        that.collection = db;
    }
    DbProvider.prototype.create = function () {
        return {
            action: function () {
                var y = {
                    printData: function () {
                        alert('Hello ' + that.collection.Name);
                    }
                };
                return y;
            }
        };
    };
    return DbProvider;
})();

var a = new DbProvider({ "Name": "John" });
a.create().action().printData();

Comments