bobek
bobek

Reputation: 8020

how to create a js prototype class in external file

I created an external .js file with prototype:

function Logger() {
    var log = new Array("");
}

Logger.prototype.AddLine = function (value) {
    if (value) {
        Logger.log.push("\t" + value);
    }
}

Logger.prototype.ReadLog = function () {
    return this.log.join("");
}

And now I try to use it on my page. I included my file in the header. And I have simple js:

$(document).ready(function () {

        var log = new Logger();
        log.AddLine("User entered the page");
});

Firebug error: TypeError: Logger.log is undefined [Break On This Error]
Logger.log.push("\t" + value);

Can anyone please explain why this is happening?

Upvotes: 0

Views: 1051

Answers (2)

Bergi
Bergi

Reputation: 665361

You are using four (!) different log things:

  • var log = new Logger(); is a (local) variable containing an new Logger instance
  • var log = new Array(""); is a (local) variable that is scoped to the constructor function it is declared in. You will not be able to access it from outside
  • Logger.log.… is a property on the Logger function object. There is nothing, so this line will throw the error.
  • this.log.… is what you actually want, a property on the current instance.

So change your script to this:

function Logger() {
    this.log = [""]; // not sure why not just an empty array
}

Logger.prototype.AddLine = function (value) {
    if (value) {
        this.log.push("\t" + value);
    }
};

Logger.prototype.readLog = function () {
    return this.log.join("");
};

Upvotes: 3

pimvdb
pimvdb

Reputation: 154948

To set log on the Logger instance to an empty array, use this.log = [], not var log. The latter creates a private variable, which you can't access outside the function.

Also, Logger.log means: access the log property on the Logger function. Here you want the instance instead, so use this.log (like you did in ReadLog).

Upvotes: 2

Related Questions