Reputation: 8020
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
Reputation: 665361
You are using four (!) different log
things:
var log = new Logger();
is a (local) variable containing an new Logger
instancevar 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 outsideLogger.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
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