Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class methods in Javascript

Tags:

javascript

oop

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?

like image 498
Channel72 Avatar asked Feb 24 '23 13:02

Channel72


2 Answers

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
like image 161
David Tang Avatar answered Mar 08 '23 14:03

David Tang


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

like image 37
Mark Cidade Avatar answered Mar 08 '23 14:03

Mark Cidade