Reputation: 2091
I have the following code:
function Tools() { }
Tools.prototype.foobar = function() {
return 'a';
};
alert(Tools.foobar());
And this code returns an error that the foobar
function was not found. Why is that so? It works without the prototype keyword.
Also, what's the difference? As far as I know I can use prototype keyword, and not use it. If it was an object I could understand that it's inheritance, but what about here?
Upvotes: 0
Views: 1675
Reputation: 63610
You did not set the property foobar
on Tools
, but instead you set it on Tools.prototype
, which means it won't be available on Tools
. If you want to call it on Tools
, you'd have to set it there:
Tools.foobar = function() { ... };
alert(Tools.foobar());
The purpose of prototype
is to specify which properties need to be contained by instances of the function. Therefore, if you want to access these properties, you should create a new instance of the function, with the new
keyword.
Tools.prototype.foobar = function() { ... };
var tools = new Tools();
alert(tools.foobar());
Upvotes: 3