Designing the class in the right way

I have some JavaScript questions I need to nail. To help, I have a simple class that I am 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 right?

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

3) Should I be bothered (2)?

+5
source share
5 answers

You have a function that returns an Object, not a JS class.

DataSource.prototype, this , new

, - :

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');

: , 'private'

- , , , _ _

+7

- , . .

+5

, .

  • - .

    function DataSource(src, extension) {
        this.src = src,
        this.extension = extension,
        this.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)
        },
        this.get = function() {
            // function will return the source (ex: return src.property.property.theSource)
        }
    }
    dataSource1 = new DataSource();
    dataSource2 = new DataSource();
    
0

. , , , .

, ( ), . , ( ExampleClass.prototype = function() {}) c/++

0

ES6 ( @tobyodavies):

class DataSource {
    constructor(src, extension) {
        this._src = src; 
        this._extension = extension; 
    }
    exists() {

    }
    get() {

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

, new, ES6. Class constructor DataSource cannot be invoked without 'new'.

0

All Articles