I'm trying to learn how to apply basic object oriented concepts to Javascript. Here, I just want to be able to create a class method, and then call the method externally when I click on an <input>
element:
<html>
<head>
<script type="text/javascript">
var Foo = function()
{
}
Foo.prototype.bar = function() { alert("blah"); }
</script>
</head>
<body>
<input type="submit" onclick = "Foo.bar()">
</body>
</html>
This doesn't work. Firefox gives the error Error: Foo.bar is not a function
However, if I call Foo()
directly, and then from within Foo
I call this.bar()
, it works fine. Why am I unable to invoke Foo.bar()
externally?
I think you're confusing so-called instance methods and class methods.
prototype
is used to create instance methods, which belong to objects created from the prototype
when used with the new
keyword:
var foo = new Foo();
foo.bar(); // Will work
I'm not sure this is what you want. More likely you just want to add a static class method to Foo
:
var Foo = {};
Foo.bar = function () { alert('blah'); };
Foo.bar(); // Will work
Instead of Foo.prototype.bar...
just use Foo.bar = function() {...}
, which will just add a bar
member on the Foo
function object.
To access any prototype
or this.*
members, you need an instance first: new Foo().bar()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With