danwoods
danwoods

Reputation: 4907

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?

Upvotes: 4

Views: 8709

Answers (4)

user1106925
user1106925

Reputation:

Well, Students doesn't have an add method.

I think you're assuming you know how this works. It isn't a reference to the function, unless you manually make it so. The value of this will depend entirely on how you call Students.

Upvotes: 1

Adam Rackis
Adam Rackis

Reputation: 83366

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

Upvotes: 3

Pointy
Pointy

Reputation: 413976

You're not adding an "add" function to the "Students" function with that code; you're adding it to instances created by using "Students" as a constructor.

var student = new Students();

student.add(); // won't get the error

Upvotes: 2

icktoofay
icktoofay

Reputation: 129119

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

Upvotes: 13

Related Questions