Channel72
Channel72

Reputation: 24719

Class methods in Javascript

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?

Upvotes: 4

Views: 867

Answers (3)

user578895
user578895

Reputation:

I wrote a few years back explains; it explains the ins-and-outs of JavaScript class structure:

http://www.htmlgoodies.com/primers/jsp/article.php/3600451/Javascript-Basics-Part-8.htm

Upvotes: 1

David Tang
David Tang

Reputation: 93664

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

Upvotes: 6

Mark Cidade
Mark Cidade

Reputation: 99957

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

Upvotes: 1

Related Questions