Reputation: 4378
I have a pretty simple function declared in my JavaScript file, which is just supposed to return whether or not the validation has begun:
window.Validator = function(){
this._started = false;
this.started = function(){
return this._started;
};
}
Validator.started();
However, when I call Validator.started()
, even though it's literally directly after the declaration, it will throw the error:
Uncaught TypeError: Validator.started is not a function
Really scratching my head with this one and have no idea why it isn't working.
Upvotes: 0
Views: 78
Reputation: 3228
this
in a function without 'use strict' points to the global object, that is window
.
So your this.started = function(){...}
is defined on the window
object. Of course, it is only defined after the Validator
is called.
So this code works, though it may not how you want to use it.
window.Validator = function(){
this._started = false;
this.started = function(){
return this._started;
};
}
Validator();
started();
console.log(_started);
If you do use 'use strict', this
is undefined
in the function definition area. You need to create an Object of Validator
, this
would be the object when you call the method.
Upvotes: 0
Reputation: 301
this
is a context. Or simply, it is an object which is on the left of dot. For example:
let v = new Validator();
v.started(); // v will be 'this' in your method
Your code:
Validator.started();
It means, that started()
is a static method of Validator
(method of exactly function Validator()
). You have to write code as I write above. Or:
window.Validator = function() {};
Validator._started = false;
Validator.started = function() {
return this._started;
};
console.log(Validator.started());
Here _started
is a static property and started()
is a static method of Validator()
.
Upvotes: 1
Reputation: 195
You should create an instance of your Validator
new Validator().started()
Upvotes: 7