Javascript class methods

I am 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 from the outside when I click on the <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 does not work. Firefox gives error Error: Foo.bar is not a function

However, if I call Foo() directly, and then from Foo I call this.bar() , it works fine. Why can't I call Foo.bar() from the outside?

+4
source share
3 answers

I think you are mixing the so-called instance methods and class methods .

prototype used to create instance methods that belong to objects created from prototype when used with the new keyword:

 var foo = new Foo(); foo.bar(); // Will work 

I am not sure if this is what you want. Most likely you just want to add a static class method to Foo :

 var Foo = {}; Foo.bar = function () { alert('blah'); }; Foo.bar(); // Will work 
+6
source

Instead of Foo.prototype.bar... just use Foo.bar = function() {...} , which will simply add the bar element to the Foo function object.

To access any members of prototype or this.* , You first need to specify an instance: new Foo().bar() .

+1
source

I wrote a few years ago; he explains all aspects of the structure of the JavaScript class:

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

+1
source

Source: https://habr.com/ru/post/1347406/


All Articles