最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript confusing Object function "has no method" error - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Jan 15, 2012 at 23:10 danwoodsdanwoods 4,90711 gold badges65 silver badges93 bronze badges 0
Add a comment  | 

4 Answers 4

Reset to default 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();

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

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

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.

发布评论

评论列表(0)

  1. 暂无评论