0

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?

3
  • did you load your script before calling it? Commented Feb 2, 2013 at 15:41
  • Yeah, but it's in document ready so it shouldn't matter anyway. Commented Feb 2, 2013 at 15:42
  • Can you check your assets if your external script has loaded? Commented Feb 2, 2013 at 15:43

2 Answers 2

3

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("");
};
Sign up to request clarification or add additional context in comments.

Comments

2

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.