Javascript confusing object function "has no method"

So I have a function that looks like this:

function Students(){ // Function add: // Returns: add page this.add = function(){ // Get template $.get('view/students/new.html', function(template){ // Templating var html = Mustache.to_html(template); // When document ready, write template to page $('document').ready(function(){ $('#container').html(html); }); }); }; }; 

When I try to call it add , do the following:
Students.add();

I get the error: Uncaught TypeError: Object function Students(){...}has no method 'add'

What gives?

+4
source share
4 answers

To use this Students implementation, you must do the following:

 var students = new Students(); students.add(); 

However, perhaps this is not what you want. You would probably want to define Students as follows:

 var Students = { add: function() { $.get( /* ... */ ); } }; 

Then you can call it like this:

 Students.add(); 
+13
source

Students must be called as a constructor .

 var s = new Students(); s.add() 

Inside Students , this will be a new object that inherits from Prorotype students and automatically returns. Therefore, speaking

 this.add = function() .... 

adds the add function to this object, which is returned. But the function will be created de novo every time this function is called. Why not add it to the prototype instead, so the function will exist only once , and will not necessarily be re-created each time.

 Students.prototype.add = function(){ 
+3
source

You do not add the "add" function to the "Students" function with this code; you add it to instances created using Students as a constructor.

 var student = new Students(); student.add(); // won't get the error 
+2
source

Well, Students does not have an add method.

I think you assume that you know how this works. This is not a function reference, unless you do it manually. The value of this will depend entirely on how you call Students .

+1
source

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


All Articles