4

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?

0

4 Answers 4

13

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();
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.