Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Designing a class the right way

Tags:

javascript

oop

I have some questions about JavaScript that I need to nail down. To help, I have a simple class definiton I'm writing:

var dataSource = function (src, extension) {
    return {
        exists: function () {
            // function to check if the source exists (src *should* be an object
            // and extension should be a string in the format ".property.property.theSource".
            // this function will return true if src.property.property.theSource exists)
        },
        get: function () {
            // function will return the source (ex: return src.property.property.theSource)
        }
    }   
}();

Questions:

1) In my current understanding of JavaScript, calling dataSource() will create a new object with its own copies of the exists() and get() methods. Am I correct?

2) Is there a way to write this so that if I create 1,000,000 dataSource objects I only have to have one copy of each function?

3) Should I even be concerned with (2)?

like image 660
JustcallmeDrago Avatar asked Jan 28 '11 07:01

JustcallmeDrago


1 Answers

What you have there is a function that returns an istance of Object, not a JS class.

You will want to check out using DataSource.prototype, and you should be adding properties to or modifying this within your constructor if you want to use this in conjunction with new

You should probably be doing something like this:

function DataSource(src, extension){
    //Make sure this behaves correctly if someone forgets to use new
    if (! this instanceof DataSource)
         return new DataSource(src,extension);
    //store the constructor arguments
    //so you can use them in the shared methods below
    this._src=src;
    this._extension=extension;
}
DataSource.prototype.exists=function(){
    //use this._src and this._extension here
    //This method will be available to all
    //objects constructed by new DataSource(...)
};
DataSource.prototype.get=function(){
    //use this._src and this._extension here
    //This method will be available to all
    //objects constructed by new DataSource(...)
};

var instance = new DataSource('a source','an extension');

Edit: You've mentioned you would prefer 'private' variables

Constructing closures is the only portable way of simulating private properties, however in my experience prefixing them with an _ and having a convention within your organisation to not rely on _ prefixed variables is sufficient in most situations

like image 64
tobyodavies Avatar answered Oct 25 '22 11:10

tobyodavies