简体   繁体   中英

How to create custom class with methods

I'm trying to create my own class for logging errors and messages to a database, but I'm new to creating custom classes and methods in Javascript. After plenty of research, I was able to put together the following code:

    function log ()
    {
    }

    log.error = function (currentFunction, logMessage)
    {
        createLog (currentFunction, logMessage, "Error");
    }

And I'm able to call the log.error function successfully with:

    log.error("current function name", "this is my error message");

My question is this: Most of the sites I looked at said to organize your code like this instead:

    function log ()
    {
        this.error = function (currentFunction, logMessage)
        {
            createLog (currentFunction, logMessage, "Error");
        }
    }

But whenever I try to call that error function, I get the following error:

Cannot find function error in object function log(currentFunction, logMessage)

Does anyone know why this is? For the sake of keeping my code clean, I would really like to be able to place everything inside one function, but at this point it looks like I may have to separate everything out, as in the first code block above.

EDIT - MY SOLUTION

Thanks to both dystroy and Jose Vega (sorry Jose, I don't have enough reputation to up-vote your answer). I ended up using dystroy's solution simply because I feel it will be easier for me to maintain my code in the future, however Jose's answer helped give me insight into what I was trying to do and the different options available to me. I feel I have a much better grasp on what's going on when you do something like var objectName = {} vs function className () {} .

Here's my new code:

    function log ()
    {
        log.prototype.error = function (currentFunction, logMessage)
        {
            createLog (currentFunction, logMessage, "Error");
        }

        log.prototype.warning = function (currentFunction, logMessage)
        {
            createLog (currentFunction, logMessage, "Warning");
        }

        log.prototype.info = function (currentFunction, logMessage)
        {
            createLog (currentFunction, logMessage, "Info");
        }

        function createLog (currentFunction, logMessage, messageType)
        {
            //code that updates MSSQL database
        }
    }

You're not using classes at all and your first function called log is totally useless as you call it.

You could have written it as

var log = {}

log.error = function (currentFunction, logMessage){
    createLog (currentFunction, logMessage, "Error");
}

Usually, when you create a new function and want to see it as a class, you do like this :

function log () {
}
log.prototype.error = function (currentFunction, logMessage) {
    createLog (currentFunction, logMessage, "Error");
}

And then you may use it like this :

(new log()).error("current function name", "this is my error message");

This looks a little like your second example, except that the error function is shared by all instances of log it you attach it to the prototype.

The MDN has a document about the object model in javascript .

I think this would be the best way to organize that log "class", you can then do warn function and info function if you wanted.

var log = {
     error : function(currentFunction, logMessage) {
          createLog(currentFunction, logMessage, "Error");
     },
     warn : function() {

     },
     info : function() {

     }
}

You could write like this:

var log = {
    error: function (currentFunction, logMessage) {
        createLog (currentFunction, logMessage, "Error");
    }
};

Then call it like this:

log.error("My function", "Is not working");

Although i usually write this using jQuery in the following fashion:

(function($) {

    //Declare object
    var _this = $.Log = new function () {

    };

    //Apply variables and methods
    $.extend(_this, {
        error: function (currentFunction, logMessage) {
            createLog (currentFunction, logMessage, "Error");
        }
    });
)(jQuery);

This would later be called like this:

$.Log.error("My function", "Is not working");

The reason the error() function can't be found is because it's inside the log object's constructor - the log() function is a constructor. That's how you make private members in Javascript, put them in the constructor. To make your error() function visible, you need to attach it to the log object's prototype, like this.

function log ()
{
    log.prototype.error = function (currentFunction, logMessage)
    {
        createLog (currentFunction, logMessage, "Error");
    }
}

Now you can call it like this:

var myLog = new log();
myLog.error("current function name", "this is my error message");

For a good article explaining public, private and protected members in javascript read this article: http://javascript.crockford.com/private.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM