Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript confusing Object function "has no method" error

So I have a function which 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's add function like so:
Students.add();

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

What gives?

like image 502
danwoods Avatar asked Dec 02 '22 00:12

danwoods


2 Answers

To use that implementation of Students, you should do this:

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

However, that's probably not what you want. You probably meant to define Students like this:

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

Then you can call it like this:

Students.add();
like image 111
icktoofay Avatar answered Dec 25 '22 07:12

icktoofay


Students is intended to be called as a constructor.

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

Inside of Students, this will be a new object that inherits from Students's prorotype, and is returned automatically. So saying

this.add = function() ....

is adding the add function onto this object that's being returned. But the function will be created de novo each and every time you invoke this function. Why not add it to the prototype instead, so the function will exist only once, and not have to be needlessly re-created each and every time.

Students.prototype.add = function(){
like image 42
Adam Rackis Avatar answered Dec 25 '22 06:12

Adam Rackis