4

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?

2
  • Have you been though the W3C schools tutorial here: w3schools.com/js ? I've been programming Javascript since it was called LiveScript and I still reference this site. Commented Apr 10, 2011 at 2:54
  • 7
    Careful with w3schools—see w3fools.com Commented Apr 10, 2011 at 2:57

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.